首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >通过python向电报机器人发送Mysql数据

通过python向电报机器人发送Mysql数据
EN

Stack Overflow用户
提问于 2018-06-20 17:17:53
回答 2查看 4.7K关注 0票数 0

我有问题,如何从Mysql检索数据,并通过Python发布到Telegram机器人。Mysql可以连接到Python,并在Python终端显示数据,但在电报中,它只显示行数。

import time
import random
import datetime
import telepot
import MySQLdb
from telepot.loop import MessageLoop

                 db = MySQLdb.connect(host="127.0.0.1",    # localhost
                 user="cowrie",         #  username
                 passwd="12345678",  #  password
                 db="cowrie")        # name of the data base
                 cur = db.cursor()

def handle(msg):
                    chat_id = msg['chat']['id']
                    command = msg['text']

print 'Command received: %s' % command

if command == '/about':
    bot.sendMessage(chat_id, 'Hi, I\'m netrapsystembot')
elif command == '/random':
    bot.sendMessage(chat_id, random.randint(0,9))
elif command == '/time':
    bot.sendMessage(chat_id, str(datetime.datetime.now()))

elif command == '/sessions':
    bot.sendMessage(chat_id, cur.execute('SELECT ip FROM sessions'))
    for result in cur.fetchall():
            print result [0]


   bot = telepot.Bot('617662632:AAEGW74VAvZcjEpVCkiye8KLcv2xmSkt0L4')

   MessageLoop(bot, handle).run_as_thread()
    print 'Bot ready!'

   while 1:
           time.sleep(10)

Python终端显示来自mysql的ip:

但电报只显示行数:

我要检索的数据是位于表会话中的ip地址。请帮帮忙。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-20 17:39:42

execute方法返回迭代器,而不是您要查找的结果。

尝试以下操作:

elif command == '/sessions':
    cur.execute('SELECT ip FROM sessions')
    for result in cur.fetchall():
        bot.sendMessage(chat_id, result [0])
票数 2
EN

Stack Overflow用户

发布于 2018-06-21 16:01:11

非常感谢你的帮助S. Phillips..它可以工作,我可以从mysql中检索数据。最后显示了IP地址的计算结果。

如果你能再帮我一次,如何使MySQL数据库在数据插入到数据库时自动(触发)将结果发送到电报。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50944601

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档