Error white creating a telegram bot

I am enrolled in Artificial Intelligence training where in module 3 there is tutorial to create a chat gpt telegram bot. But when I execute the code below it shows an error as seen in the screenshot.

I have seen the aiogram documentation and it turns out that executor is entirely removed from the library due to which the error is occurring. Please help to provide a workaround for this.

Hi @abdullahmd2002,

The error you’re encountering, ImportError: cannot import name 'executor' from 'aiogram' , indicates that the aiogram library doesn’t have an executor attribute.
To fix this issue, you should remove the executor import from the aiogram package. Instead, you can use the executor from aiogram.dispatcher :

from aiogram import Bot, Dispatcher, types
from aiogram.dispatcher import executor

Try this and let me know if it works.

Hi @rohit.ts,

I tried importing executor from aiogram.dispatcher but still getting import error in this as well.

ImportError: cannot import name 'executor' from 'aiogram.dispatcher'

Hi @abdullahmd2002,

To work around the removal of the executor in the aiogram library, you’ll need to handle the polling loop yourself. Here’s a modified version of your main.py to achieve this:

import os
import openai
from aiogram import Bot, Dispatcher, types
from aiogram.types import ParseMode
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.utils import executor
from example import example

bot = Bot(token='YOUR_BOT_TOKEN')
dp = Dispatcher(bot)
openai.api_key = os.environ['OPENAI_API_KEY']
example()


@dp.message_handler(commands=['start', 'help'])
async def welcome(message: types.Message):
    await message.reply('Hello! I am GPT Chat BOT. You can ask me anything :)')


@dp.message_handler()
async def gpt(message: types.Message):
    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=message.text,
        temperature=0.5,
        max_tokens=1024,
        top_p=1,
        frequency_penalty=0.0,
        presence_penalty=0.0
    )
    await message.reply(response.choices[0].text, parse_mode=ParseMode.HTML)


async def on_startup(dp):
    logging_middleware = LoggingMiddleware()
    dp.middleware.setup(logging_middleware)


if __name__ == "__main__":
    from aiogram import executor

    executor.start_polling(dp, skip_updates=True, on_startup=on_startup)

The main change is in the last block where we import executor and use it to start polling. We also define an on_startup function to set up any middleware (in this case, a logging middleware). Adjust the YOUR_BOT_TOKEN to your actual bot token. Make sure you have the necessary dependencies installed (aiogram , openai , etc.).

Let me know if this works.

The new version is not accepting the executors instead you may use start polling method without executor or go to prompt and pip install aiogram==2.5 version and run the same program it will connect to telegram bot

The possible error is due to the fact that executor has been removed from the latest updates. Instead we can use alternative method to start polling. there have been some other changes as well, like handler suffix was removed from ‘message_handler’, Dispatcher class does not expect to receive the bot argument in its constructor, the following code should fix all :
import os
import openai
import asyncio
from aiogram import Bot, Dispatcher, types
from example import example

bot = Bot(token=‘Your Token Key’)

dp = Dispatcher()
openai.api_key = os.environ[‘OPENAI_API_KEY’]
example()
@dp.message()
async def gpt(message: types.Message):
response = openai.Completion.create(model=“text-davinci-003”,
prompt=message.text,
temperature=0.5,
max_tokens=1024,
top_p=1,
frequency_penalty=0.0,
presence_penalty=0.0)
await message.reply(response.choices[0].text)
async def main():
await dp.start_polling(bot)
if name == “main”:
asyncio.run(main())

#example module is same as provided in course.

it generates completion error


i have used the same code


see my chat not working

Hi @laditi454

There are few errors in your code related to OpenAI library. Also mention your actual telegram bot token on line number 7. Below I’m attaching entire code for telegram chatbot. Please do try this and let me know. Make sure that you have set up the telegram bot correctly before writing the code.

main.py:

import os

import openai

from aiogram import Bot, Dispatcher, executor, types

from example import example

bot = Bot(token='REPLACE THIS WITH YOUR TELEGRAM BOT TOKEN')

dp = Dispatcher(bot)

#Replace 'OPENAI_API_KEY' with your actual OpenAI API key OR keep it as it is and enter the OpenAI api key in the secrets section on Replit
openai.api_key = os.environ['OPENAI_API_KEY']

example()


@dp.message_handler(commands=['start', 'help'])
async def welcome(message: types.Message):

  await message.reply('Hello! I am GPT Chat BOT. You can ask me anything :)')


@dp.message_handler()
async def gpt(message: types.Message):

  response = openai.completions.create(model="gpt-3.5-turbo-instruct",
                                       prompt=message.text,
                                       temperature=0.5,
                                       max_tokens=1024,
                                       top_p=1,
                                       frequency_penalty=0.0,
                                       presence_penalty=0.0)

  await message.reply(response.choices[0].text)


if __name__ == "__main__":

  executor.start_polling(dp)

Replace the Bot token and OpenAI API key with your actual keys.

example.py:

from flask import Flask, render_template

from threading import Thread

app = Flask(__name__)

@app.route('/')

def index():

 return "example" 

def run():

 app.run(host='0.0.0.0',port=8080) 

def example():

 t = Thread(target=run)

 t.start()


Do try this and let us know. If you still face issues, please feel free to get back to us.

The error that you are facing indicates an executor attribute is missing from the library used. So in order to fix this problem you should import the executor from the package named aiogram.