[英]Telegram Bot respond to specific command in Python list
我正在制作一個可以訪問數據庫以回復用戶查詢的Telegram機器人。 機器人需要響應數據庫中某些數據的特定請求。 當用戶請求所有數據時,我能夠解決問題,但是我只能使用單個數據。 我使用telegram.ext
從telegram
在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()
我正在尋找一種方法,將當前命令(也是用戶在currr[]
列表中請求的數據庫中的ID)傳遞給currr[]
individualreq(bot, update)
函數,以便僅對被調用ID的數據進行復制。 用戶將從電報中的ID列表中進行選擇,命令處理程序可以將所選的ID傳遞給函數。 我還沒有找到將ID傳遞給函數的方法。 有人可以幫我解決這個問題。 謝謝
我從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
您可以直接將 individualreq
封閉。
CommandHandler
接受一個命令或命令列表以進行偵聽,並列出其他選項。 有一個pass_user_data
選項 ,該選項允許將用戶數據傳遞給回調。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.