skip to Main Content

This is my code

from telegram.ext import Updater, CommandHandler
import os
from pymongo import MongoClient

TOKEN = 'TOKEN'

def get_db(update, context):
    cluster = MongoClient("mongodb+srv://testing:[email protected]/test?retryWrites=true&w=majority")
    result = list(cluster.get_database('DBNAME')['COLLECTIONNAME'].find({}))
    update.message.reply_text(str(result))

def main():
    updater = Updater(TOKEN, use_context=True)
    dp = updater.dispatcher

    dp.add_handler(CommandHandler("getdb", get_db))

    updater.start_webhook(listen="#.#.#.#",
                          port=int(PORT),
                          url_path=TOKEN)
    updater.bot.setWebhook('https://MYHEROKUAPP.herokuapp.com/' + TOKEN)

    updater.idle()


if __name__ == '__main__':
    main()

Everytime I type /getdb, the bot doesn’t give me any response. When I tried several experiments, Seems there’s some Error on cluster variable. I used try except syntax, but the bot didn’t show anything, even from the except and I couldn’t found the Error name as well. And I’m using heroku server for the telegram bot. How to fix this?

2

Answers


  1. You can connect to default db (which is the one defined in the connection string) and query the collections like this

    client = MongoClient('connect-string')
    db = client.get_default_database()
    # 'collection_name' is the name of the Mongo collection
    list = db.collection_name.find()
    
    Login or Signup to reply.
  2. I’m not sure if you still have this issue, but the code seems to be okay so far.
    Try logging the app info to the terminal to get a better idea of what the error is.

    import logging
    logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                            level=logging.INFO)
    logger = logging.getLogger(__name__)
    
    1. It may be that your MongoDB Atlas is not allowing connection from the server you are running your code from. You can check your cluster to see if it allows access to the DB from your server. You can add the IP address of your server to the cluster to allow it succesfully access the data.
    2. If the collection you’re trying to display all items from is large, Telegram will throw an error because the ensuing message will be too long. Ensure that you’re running your test with only a few items in your test database.
    3. You should be ale to check your heroku logs or in your terminal to see what other errors might be happening
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search