Visual Studio Code中的机器人
在Python上无法工作的Telegram机器人:
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时出现了一个警告:
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 个回答
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.infinity_polling()
移到那个函数外面,这样至少可以让它开始运行。
@bot.message_handler(func=lambda m: True)
def echo_all(message):
...
bot.infinity_polling()