讓你的AI Agent接入電報機器人!
作者:JavaEdge
萬事萬物都經不起審視,因為世上沒有同樣的成長環境,也沒有同樣的認知水平,更「沒有適用于所有人的解決方案」。
0.數據架構
+-----+
| TTS |
+--+--+
|
v
+------------+
| Server api |
+-----+------+
|
+-----v-----+
| Agent |
+-----+-----+
| |
+---v---+ +-v------+
| tools | | memory |
+-------+ +--------+
從 memory 向上流動到TTS,再向下流動到tools。
1.申請機器人KEY
搜索關注 BotFather,注意有藍標官方認證的,很多假冒,如:
圖片
這個才是正版!
圖片
1.1 新建一個機器人
圖片
1.2 編輯機器人信息
圖片
編輯“關于”信息:
圖片
設置機器人頭像
圖片
行了,直接訪問 bot 吧!
圖片
2.引入telebot包
import telebot
# 之前獲取的 user token
bot = telebot.TeleBot('xxx:xxx')
3.編寫客戶端代碼
@bot.message_handler(commands=['start'])
def start_message(message):
bot.send_message(message.chat.id, '你好我是JavaEdge,歡迎光臨!')
python tele-qwen.py
啟動項目,對話 bot,即可看到
3.1 指定回復
圖片
3.2 引用&&回復
@bot.message_handler(commands=['start'])
def start_message(message):
bot.reply_to(message, '你好!')
4.將 bot 關聯到 server 端
即關聯到 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, "對不起,我不知道怎么回答你")
except requests.RequestException as e:
bot.reply_to(message, "對不起,我不知道怎么回答你")
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 的回復響應給 tg 用戶:
圖片
參考:
- tg api
完整專欄內容,盡在編程嚴選網免費閱讀學習:
圖片
責任編輯:武曉燕
來源:
JavaEdge