讓你的AI Agent接入電報(bào)機(jī)器人!
作者:JavaEdge
萬(wàn)事萬(wàn)物都經(jīng)不起審視,因?yàn)槭郎蠜](méi)有同樣的成長(zhǎng)環(huán)境,也沒(méi)有同樣的認(rèn)知水平,更「沒(méi)有適用于所有人的解決方案」。
0.數(shù)據(jù)架構(gòu)
+-----+
| TTS |
+--+--+
|
v
+------------+
| Server api |
+-----+------+
|
+-----v-----+
| Agent |
+-----+-----+
| |
+---v---+ +-v------+
| tools | | memory |
+-------+ +--------+
從 memory 向上流動(dòng)到TTS,再向下流動(dòng)到tools。
1.申請(qǐng)機(jī)器人KEY
搜索關(guān)注 BotFather,注意有藍(lán)標(biāo)官方認(rèn)證的,很多假冒,如:
圖片
這個(gè)才是正版!
圖片
1.1 新建一個(gè)機(jī)器人
圖片
1.2 編輯機(jī)器人信息
圖片
編輯“關(guān)于”信息:
圖片
設(shè)置機(jī)器人頭像
圖片
行了,直接訪(fǎng)問(wèn) bot 吧!
圖片
2.引入telebot包
import telebot
# 之前獲取的 user token
bot = telebot.TeleBot('xxx:xxx')
3.編寫(xiě)客戶(hù)端代碼
@bot.message_handler(commands=['start'])
def start_message(message):
bot.send_message(message.chat.id, '你好我是JavaEdge,歡迎光臨!')
python tele-qwen.py
啟動(dòng)項(xiàng)目,對(duì)話(huà) bot,即可看到
3.1 指定回復(fù)
圖片
3.2 引用&&回復(fù)
@bot.message_handler(commands=['start'])
def start_message(message):
bot.reply_to(message, '你好!')
4.將 bot 關(guān)聯(lián)到 server 端
即關(guān)聯(lián)到 chat 接口:
@bot.message_handler(func=lambda message: True)
def echo_all(message):
# bot.reply_to(message, message.text)
try:
encoded_text = urllib.parse.quote(message.text)
response = requests.post('http://localhost:8090/chat?query=' + encoded_text, timeout=100)
if response.status_code == 200:
ai_say = json.loads(response.text)
if "msg" in ai_say:
bot.reply_to(message, ai_say["msg"]["output"])
audio_path = f"{ai_say['id']}.mp3"
asyncio.run(check_audio(message, audio_path))
else:
bot.reply_to(message, "對(duì)不起,我不知道怎么回答你")
except requests.RequestException as e:
bot.reply_to(message, "對(duì)不起,我不知道怎么回答你")
async def check_audio(message, audio_path):
while True:
if os.path.exists(audio_path):
with open(audio_path, 'rb') as f:
bot.send_audio(message.chat.id, f)
os.remove(audio_path)
break
else:
print("waiting")
await asyncio.sleep(1)
bot.infinity_polling()
這樣就能將 LLM 的回復(fù)響應(yīng)給 tg 用戶(hù):
圖片
參考:
- tg api
完整專(zhuān)欄內(nèi)容,盡在編程嚴(yán)選網(wǎng)免費(fèi)閱讀學(xué)習(xí):
圖片
責(zé)任編輯:武曉燕
來(lái)源:
JavaEdge