这是我的 Telegram Bot 的简化代码
import telegram.bot, telegram, sqlite3
from telegram.ext import Updater,CommandHandler,MessageHandler,Filters
class DatabaseManager(object):
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.conn.execute('pragma foreign_keys = on')
self.conn.commit()
self.cur = self.conn.cursor()
def query(self, arg):
self.cur.execute(arg)
self.conn.commit()
return self.cur
def __del__(self):
self.conn.close()
def regcheck(uid):
for row in dbmgr.query("SELECT * FROM users WHERE id="+str(uid)+";"):
print "regcheck is running" #this is never printed
if row == "":
return 1
else:
return 0
def start(bot, update):
if regcheck(update.message.chat_id) == 1:
bot.send_message(chat_id=update.message.chat_id, text="OK")
else:
bot.send_message(chat_id=update.message.chat_id,text="FAIL")
def main():
global dbmgr
dbmgr = DatabaseManager("usr.sql")
for row in dbmgr.query("select * from users WHERE id="+str(uid)+";"):
print row #this works perfectly fine
updater = Updater(token=token)
dispatcher = updater.dispatcher
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
我知道,为 dbmgr
使用全局变量不是最佳选择,但这是我的第一个 python-telegram-bot
项目,我不知道一种(更好的,或者至少是有效的)方法来实现这一点。
为什么 main()
中的 row
被打印,而 regcheck()
中的 dbmgr.query
被打印> 卡住了?
最佳答案
尝试更改 SQLite 连接的初始化:
self.conn = sqlite3.connect(db, check_same_thread=False)
在这里阅读更多信息:
关于python - python-telegram-bot 中的 SQLite 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47490444/