ybaidukuai 发表于 2018-8-14 07:30:24

python QQ机器人 (转载)

  通过第三方库qqbot来实现,pip install qqbot 直接安装就行
  脚本直接运行会弹出二维码,手机qq扫码登录即可
  通过#weather# city 来查询天气预报
  通过#study# key value 来进行学习,以json格式存储在指定文件
  第一次运行没有这个json文件,可以手动创建一个,内容为一对英文的双引号即可
  通过#get# key 来进行获取之前存储的内容
  只能在qq群进行自动操作
  #!/usr/bin/env python
  # -*- coding:utf-8 -*-
  import requests
  import qqbot
  import json
  mess = json.load(open('qq.txt', 'r'))
  def weather(city):
  r = city
  url = 'http://www.sojson.com/open/api/weather/json.shtml?city=' + city
  html = requests.get(url)
  result = json.loads(html.text)
  if result.get('status') != 200:
  return "暂无【%s】天气预报!" % city
  res = result.get('data').get('forecast')
  for i in res:
  r += '\r\n' + i.get('date') + ' ' + i.get('type') + ' ' + i.get('low') + ' ' + i.get('high') + ' ' + i.get(
  'fengli') + ' ' + i.get('fengxiang')
  return r
  @qqbot.QQBotSlot
  def onQQMessage(bot, contact, member, content):
  if "@ME" in content:
  con = '圈我干啥??'
  bot.SendTo(contact, con)
  elif content.startswith("#study#") and '#get#' not in content and len(content.split()) >= 3:
  key, *value = content.split()
  mess = value
  con = "录入成功!"
  json.dump(mess, open('qq.txt', 'w'))
  bot.SendTo(contact, con)
  elif content.startswith('#get#') and len(content.split()) >= 2:
  key = content.split()
  con = mess.get(key) if key in mess else '不存在'
  bot.SendTo(contact, ' '.join(con))
  elif content.startswith("#weather#") and len(content.split()) >= 2:
  con = weather(content.split())
  bot.SendTo(contact, con)
  if __name__ == '__main__':
  qqbot.RunBot()
页: [1]
查看完整版本: python QQ机器人 (转载)