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

Send Mysql data to telegram bot via python

我有问题,如何通过 Python 从 Mysql 和 post 检索数据到 Telegram Bot。 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

但电报只显示行数:

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

execute 方法returns 一个迭代器而不是您要查找的结果。

尝试以下操作:

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

非常感谢您的帮助 S. Phillips.. 它有效,我可以从 mysql 检索数据。终于显示IP地址的结果了。

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