4

When I run this code:

from telegram.ext import *
import keys
    
print('Starting a bot....')
     
def start_commmand(update, context):
    update.message.reply_text('Hello! Welcome To Store!')

if __name__ == '__main__':
    updater = Updater(keys.token, True)
    dp = updater.dispatcher

    # Commands
    dp.add.handler(CommandHandler('start', start_commmand))

    # Run bot
    updater.start_polling(1.0)
    updater.idle()

I get this error:

Traceback (most recent call last):
  File "C:\Users\pc\PycharmProjects\telegram\main.py", line 11, in <module>
    dp = updater.dispatcher
AttributeError: 'Updater' object has no attribute 'dispatcher'

I attempted to resolve this issue by updating the library but the error remained.

Michael M.
  • 10,486
  • 9
  • 18
  • 34

2 Answers2

5

You probably found an example for v13, but since a few days the v20 for python-telegram-bot is out. Now you have to build your application differently and you have to use async functions.

This should work:

from telegram.ext import *
import keys
    
print('Starting a bot....')
     
async def start_commmand(update, context):
    await update.message.reply_text('Hello! Welcome To Store!')

if __name__ == '__main__':
    application = Application.builder().token(keys.token).build()

    # Commands
    application.add_handler(CommandHandler('start', start_commmand))

    # Run bot
    application.run_polling(1.0)

Also, here are some good examples for the python-telegram-bot library.

Cydog
  • 360
  • 3
  • 8
  • 1
    @AbdullahSultan happy to hear that! Please accept the answer, so your question is marked as answered. – Cydog Jan 03 '23 at 15:47
0

Check recent changelogs I found a bug fix for versions >= 20.0a0 where dispatcher is no longer used, but if you want to run your script in that version you need to install it pip install python-telegram-bot==13.3

from telegram import Update, ForceReply
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext 

def start(update: Update, _: CallbackContext) -> None:
    user = update.effective_user
    update.message.reply_markdown_v2(
        fr'Hi {user.mention_markdown_v2()}\!',
        reply_markup=ForceReply(selective=True),
    )


def help_command(update: Update, _: CallbackContext) -> None:
    update.message.reply_text('Help!') 

def run_bot(update: Update, _: CallbackContext) -> None:
    replica = update.message.text
    answer = bot(replica)
    update.message.reply_text(answer) 

    print(replica)
    print(answer)
    print()
    
def main() -> None:
    updater = Updater("token")
    dispatcher = updater.dispatcher
    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(CommandHandler("help", help_command))
    dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, run_bot))

    # Initialize bot
    updater.start_polling()

    updater.idle()

main()
user11717481
  • 1
  • 9
  • 15
  • 25