Telegram Bot响应Python列表中的特定命令

时间:2017-09-13 08:17:51

标签: python telegram python-telegram-bot

我正在制作一个可以访问数据库以回复用户的Telegram机器人。查询。机器人需要响应数据库中某些数据的特定请求。当用户请求所有数据时,我能够解决这个问题,但我遇到了个别数据。我在python中使用来自telegram.ext包的telegram。这是我到目前为止所做的。

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()

我正在寻找一种方法来传递当前命令,该命令也是用户在currr[]列表中请求的数据库中的ID到individualreq(bot, update)函数,以便只有被叫ID的数据正在回答。用户将从电报中的ID列表中进行选择,命令处理程序可以将所选ID传递给该函数。我还没有找到将ID传递给函数的方法。请有人帮我解决这个问题。感谢

2 个答案:

答案 0 :(得分:1)

我从Oluwafemi Sule提供的答案中找到了我的问题的解决方案。 CommandHandler可以通过在pass_args=True中添加CommandHandler将命令的参数传递给函数。

dp.add_handler(CommandHandler(currr, individualreq, pass_args=True))

要打印出函数中的参数,该函数需要接收参数。

def individualreq(bot, update, args):
    # id store the args value
    id = update.message.text
    print(id[1:]) # [1:] is to get rid of the / in id

答案 1 :(得分:0)

你可以直接使individualreq成为封闭。

CommandHandler接受一个命令或命令列表来监听和列出其他选项。 There is a pass_user_data option允许将用户数据传递给回调。

dp.add_handler(CommandHandler(currr, individualreq, pass_user_data=True))

individualreq回调的签名将更新为user_data

def individualreq(bot, update, user_data=None):
     #user_data is a dict
     print(user_data)