我正在制作一个可以访问数据库以回复用户查询的Telegram机器人。机器人需要响应数据库中某些数据的特定请求。我能够解决用户请求所有数据时的情况,但我坚持使用单个数据。我正在使用telegram.ext
从telegram
包在Python中。这是我迄今为止所做的。Telegram Bot响应Python列表中的特定命令
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import MySQLdb
currr = [] # global list var ~don't bash me for using global in python please, I'm a newbie
# request for all data in database
def request2(bot, update):
db = MySQLdb.connect(host = "local", user = "root", passwd = "pwd", db = "mydb")
cur = db.cursor()
cur.execute("select ID from table")
ID = cur.fetchall()
cur.execute("SELECT ID, temp FROM table2 order by indexs desc")
each_rows = cur.fetchall()
for IDs in ID:
for each_row in each_rows:
if str(each_row[0])[0:4]==str(ID)[2:6]:
update.message.reply_text('reply all related data here')
break
# request for single data
def individualreq(bot, update):
db = pymysql.connect(host = "localhost", user = "root", passwd = "pwd", db = "mydb")
update.message.reply_text('reply individual data to users here')
def main():
updater = Updater("TOKEN")
dp = updater.dispatcher
global currr
# get all ID form database
db = MySQLdb.connect(host = "localhost", user = "root", passwd = "pwd", db = "mydb")
cur = db.cursor()
cur.execute("select ID from table")
curr_ID = cur.fetchall()
# example ID = 'F01', 'F02', 'F03'
for curr_IDs in curr_ID:
currr.append(curr_IDs[0])
# request all data
dp.add_handler(CommandHandler("all", request2))
# request individual data
dp.add_handler(CommandHandler(currr, individualreq)) # list command in currr[]
if __name__ == '__main__':
main()
我正在寻找一种方式来传递当前的命令,这也是在数据库中的ID,在currr[]
列表中individualreq(bot, update)
功能,用户请求,这样,被叫ID的唯一数据是被回答。用户将从电报中的ID列表中进行选择,并且命令处理程序可以将选定的ID传递给该功能。我还没有找到一种方法将ID传递给函数。有人可以帮我解决这个问题。谢谢
我试过这个,但输出只有一个空白的括号[]。我也尝试过'pass_args = True',但输出是一样的。 –
您是否在轮询调度程序并使用用户帐户进行测试? –
是的,我正在使用用户帐号进行轮询和测试。 bot也可以回复电报组。 –