Visual Studio Code 中的 Python 机器人?

问题描述 投票:0回答:1

无法在 Python 上运行 Telegram Bot:

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()

动作顺序如下:

  • 通过 BotFather 创建 Telegram 机器人。
  • 已安装 Visual Studio Code。
  • 安装了Python。
  • 安装了 Visual Studio Code 的 Python 扩展。
  • 安装了 pyTelegramBotAPI 库。
  • 使用上面编写的代码在项目文件夹中创建main.py。

我运行 main.py 但它不起作用?可能是什么问题?

附注安装pyTelegramBotAPI时出现警告:

警告:脚本 normalizer.exe 安装在“C:\Users\Admin\AppData\Roaming\Python\Python312\Scripts”中,该路径不在 PATH 上。 考虑将此目录添加到 PATH,或者,如果您想抑制此警告,请使用 --no-warn-script-location。

谢谢!

python visual-studio-code telegram-bot python-telegram-bot
1个回答
0
投票

与 VSCode 相关的任何内容都与问题无关。如果这确实是您的全部代码,那么问题就在这里:

@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()

您在一个从未调用的函数中启动您的机器人。将

bot.infinit_polling()
从该函数中移出,它至少应该启动。

@bot.message_handler(func=lambda m: True)
def echo_all(message):
   ...
    
bot.infinity_polling()
© www.soinside.com 2019 - 2024. All rights reserved.