Bot in Visual Studio Code

95 Views Asked by At

Not working Telegram Bot on Python:

import telebot
import google.generativeai as genai
bot = telebot.TeleBot("API KEY", parse_mode=None) # You can set parse_mode by default. HTML or MARKDOWN
genai.configure(api_key="API KEY")

# Set up the model
generation_config = {
  "temperature": 0.9,
  "top_p": 1,
  "top_k": 1,
  "max_output_tokens": 2048,
}

safety_settings = [
  {
    "category": "HARM_CATEGORY_HARASSMENT",
    "threshold": "BLOCK_MEDIUM_AND_ABOVE"
  },
  {
    "category": "HARM_CATEGORY_HATE_SPEECH",
    "threshold": "BLOCK_MEDIUM_AND_ABOVE"
  },
  {
    "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
    "threshold": "BLOCK_MEDIUM_AND_ABOVE"
  },
  {
    "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
    "threshold": "BLOCK_MEDIUM_AND_ABOVE"
  },
]

model = genai.GenerativeModel(model_name="gemini-1.0-pro",
                              generation_config=generation_config,
                              safety_settings=safety_settings)

convo = model.start_chat(history=[
  {
    "role": "user",
    "parts": ["Привіт!"]
  },
  {
    "role": "model",
    "parts": ["Привіт, чим можу допомогти?"]
  },
])

@bot.message_handler(func=lambda m: True)
def echo_all(message):
    convo.send_message(message.text)
    response = (convo.last.text)
    bot.reply_to(message, response)
    
    bot.infinity_polling()

The sequence of actions is as follows:

  • Created Telegram Bot through BotFather.
  • Installed Visual Studio Code.
  • Installed Python.
  • Installed the Python extension for Visual Studio Code.
  • Installed the pyTelegramBotAPI library.
  • Created main.py in the project folder with the code written above.

I run main.py but it doesn't work? What could be the problem?

P.S. There was a warning when installing pyTelegramBotAPI:

WARNING: The script normalizer.exe is installed in 'C:\Users\Admin\AppData\Roaming\Python\Python312\Scripts' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
1

There are 1 best solutions below

2
Teemu Risikko On

None of the stuff related to VSCode matter for the problem. If that's really all of your code, the issue is here:

@bot.message_handler(func=lambda m: True)
def echo_all(message):
    convo.send_message(message.text)
    response = (convo.last.text)
    bot.reply_to(message, response)
    
    bot.infinity_polling()

You start your bot within a function you never call. Move bot.infinity_polling() out of that function and it should at least start.

@bot.message_handler(func=lambda m: True)
def echo_all(message):
   ...
    
bot.infinity_polling()