3

This is the simplified code for my 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()

I understand, that using a global variable for dbmgr is sub-optimal, but this is my first python-telegram-bot project, and I am not aware of a (better, or at least working) way to accomplish this.

Why does row in the main() get printed, but the dbmgr.query in regcheck() gets stuck?

4
  • try adding global dbmgr at the beginning of def regcheck Commented Nov 27, 2017 at 1:01
  • SQLite objects created in a thread can only be used in that same thread. Commented Jan 3, 2018 at 18:01
  • @BartVanLoon so how can we add the sqlite to the main thread? do you know any way? thanks. Commented Apr 9, 2018 at 13:31
  • not from the top of my head, sorry. I use simple CSV files as the data storage backend for my python-telegram-bots. for simple use cases this is as workable as sqlite for me. Commented Apr 10, 2018 at 20:12

1 Answer 1

1

Try to change initialization of SQLite connection:

self.conn = sqlite3.connect(db, check_same_thread=False)

Read more about here:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.