Python ChatGPT Telegram Bot
注册
这里如何注册我就不说明了,大家自行去注册,主要是现在GPT的基本上已经备用很多了,导致了接码的价格也上涨了,而且使用token的话,其实还是很快可以用完免费的18美金;
接码:https://sms-activate.org/
准备材料
主要提供下Python的实现代码,首先需要准备一下的东西:
- Telegram Bot 的 Key :找机器人爸爸获取
- ChatGPT 的 API Key : https://platform.openai.com/account/api-keys
脚本:
# 1. Start by importing the necessary libraries and setting up the API clients
import requests
import json
import os
import threading
# OpenAI secret Key
API_KEY = 'xxxxxxxxx'
# Models: text-davinci-003,text-curie-001,text-babbage-001,text-ada-001
MODEL = 'text-davinci-003'
# Telegram secret access bot token
BOT_TOKEN = 'xxxxxxxxxxxxx'
# Defining the bot's personality using adjectives
BOT_PERSONALITY = ''
# 2a. Function that gets the response from OpenAI's chatbot
def openAI(prompt):
# Make the request to the OpenAI API
response = requests.post(
'https://api.openai.com/v1/completions',
headers={'Authorization': f'Bearer {API_KEY}'},
json={'model': MODEL, 'prompt': prompt, 'temperature': 0.4, 'max_tokens': 4000}
)
result = response.json()
print(result)
final_result = ''.join(choice['text'] for choice in result['choices'])
return final_result
# 2b. Function that gets an Image from OpenAI
def openAImage(prompt):
# Make the request to the OpenAI API
resp = requests.post(
'https://api.openai.com/v1/images/generations',
headers={'Authorization': f'Bearer {API_KEY}'},
json={'prompt': prompt, 'n': 1, 'size': '1024x1024'}
)
response_text = json.loads(resp.text)
return response_text['data'][0]['url']
# 3a. Function that sends a message to a specific telegram group
def telegram_bot_sendtext(bot_message, chat_id, msg_id):
data = {
'chat_id': chat_id,
'text': bot_message,
'reply_to_message_id': msg_id
}
response = requests.post(
'https://api.telegram.org/bot' + BOT_TOKEN + '/sendMessage',
json=data
)
return response.json()
# 3b. Function that sends an image to a specific telegram group
def telegram_bot_sendimage(image_url, group_id, msg_id):
data = {
'chat_id': group_id,
'photo': image_url,
'reply_to_message_id': msg_id
}
url = 'https://api.telegram.org/bot' + BOT_TOKEN + '/sendPhoto'
response = requests.post(url, data=data)
return response.json()
# 4. Function that retrieves the latest requests from users in a Telegram group,
# generates a response using OpenAI, and sends the response back to the group.
def Chatbot():
# Retrieve last ID message from text file for ChatGPT update
cwd = os.getcwd()
filename = cwd + '/chatgpt.txt'
if not os.path.exists(filename):
with open(filename, "w") as f:
f.write("1")
else:
print("File Exists")
with open(filename) as f:
last_update = f.read()
# Check for new messages in Telegram group
url = f'https://api.telegram.org/bot{BOT_TOKEN}/getUpdates?offset={last_update}'
response = requests.get(url)
data = json.loads(response.content)
for result in data['result']:
try:
# Checking for new message
if float(result['update_id']) > float(last_update):
# Checking for new messages that did not come from chatGPT
if not result['message']['from']['is_bot']:
last_update = str(int(result['update_id']))
# Retrieving message ID of the sender of the request
msg_id = str(int(result['message']['message_id']))
# Retrieving the chat ID
chat_id = str(result['message']['chat']['id'])
# Checking if user wants an image
if '/img' in result['message']['text']:
prompt = result['message']['text'].replace("/img", "")
bot_response = openAImage(prompt)
print(telegram_bot_sendimage(bot_response, chat_id, msg_id))
# Checking that user mentionned chatbot's username in message
if '@chatGpt_dandelion_bot' in result['message']['text'] \
or '/ask' in result['message']['text']:
prompt = result['message']['text'].replace("@chatGpt_dandelion_bot", "")
# Calling OpenAI API using the bot's personality
bot_response = openAI(f"{BOT_PERSONALITY}{prompt}")
# Sending back response to telegram group
print(telegram_bot_sendtext(bot_response, chat_id, msg_id))
# Verifying that the user is responding to the ChatGPT bot
if 'reply_to_message' in result['message']:
if result['message']['reply_to_message']['from']['is_bot']:
prompt = result['message']['text']
bot_response = openAI(f"{BOT_PERSONALITY}{prompt}")
print(telegram_bot_sendtext(bot_response, chat_id, msg_id))
except Exception as e:
print(e)
# Updating file with last update ID
with open(filename, 'w') as f:
f.write(last_update)
return "done"
# 5 Running a check every 5 seconds to check for new messages
def main():
timertime = 5
Chatbot()
# 5 sec timer
threading.Timer(timertime, main).start()
# Run the main function
if __name__ == "__main__":
main()
Python ChatGPT Telegram Bot的更多相关文章
- Python+chatGPT编程5分钟快速上手,强烈推荐!!!
最近一段时间chatGPT火爆出圈!无论是在互联网行业,还是其他各行业都赚足了话题. 俗话说:"外行看笑话,内行看门道",今天从chatGPT个人体验感受以及如何用的角度来分享一下 ...
- zabbix+telegram的API接口(告警)
首先在telegram里创建一个有API接口的用户,创建是在 @BotFather 选择/start——————/newbot 输入机器人的用户名,根据提示操作.获得bot的API接口和群ID 通 ...
- 基于 .NET7.0 开发Telegram 机器人(入门)
简介 Telegram(非正式简称TG.电报)是跨平台的即时通信软件,其客户端是自由及开放源代码软件,但服务端是专有软件.用户可以相互交换加密与自毁消息,发送照片.视频等所有类型文件.官方提供手机版( ...
- 精选 TOP45 值得学习的Python项目
精选 TOP45 值得学习的Python项目 [导读]热门资源博客 Mybridge AI 比较了 18000 个关于 Python 的项目,并从中精选出 45 个最具竞争力的项目.我们进行了翻译,在 ...
- 值得收藏的45个Python优质资源
REST API:使用 Python,Flask,Flask-RESTful 和 Flask-SQLAlchemy 构建专业的 REST API https://www.udemy.com/rest- ...
- 值得收藏的45个Python优质资源(附链接)
REST API:使用 Python,Flask,Flask-RESTful 和 Flask-SQLAlchemy 构建专业的 REST API https://www.udemy.com/rest- ...
- Python学习教程(十)精选 TOP45 值得学习的Python项目
精选 TOP45 值得学习的Python项目 [导读]热门资源博客 Mybridge AI 比较了 18000 个关于 Python 的项目,并从中精选出 45 个最具竞争力的项目.我们进行了翻译,在 ...
- ChatGPT推荐最常用的自动化测试、性能、安全测试工具!
ChatGPT是一种当前被广泛关注的人工智能技术,它具备生成自然语言的能力,能够完成一些简单的文本生成.对话交互等任务.ChatGPT 算法的出现,打破了以前自然语言处理的瓶颈,使得机器具备了更加贴合 ...
- 一款能“干掉” ChatGPT 的应用「GitHub 热点速览」
据说有了它,ChatGPT 就可以靠边站了.因为 Auto-GPT 能更加主动地完成你给他的指定任务,不用做更多的人为干涉,它的推理能力比 ChatGPT 更强,有人用它解放双手做了个 React 网 ...
- Awesome Go
A curated list of awesome Go frameworks, libraries and software. Inspired by awesome-python. Contrib ...
随机推荐
- 国际顶刊《PNAS》:爱发朋友圈的人,更容易长寿
点上面关注我们,每日获取前沿新知 近几十年来,智能手机和网络的普及率越来越高,与此同时,"朋友圈"应运而生. 在这个朋友圈里,有人十分活跃,而也有些人是"国家级潜水运动员 ...
- 明解STM32—GPIO应用设计篇之IO外部中断EXTI原理及使用方法
一.前言 在之前针对STM32的GPIO相关API函数及配置使用进行了详细的介绍,GPIO作为输入引脚时,调用相关读信号引脚函数接口就可以在程序的循环中,轮询的对输入信号进行读取检测操作,除了轮询的 ...
- CoaXpress downlink数据解析方法
什么是downlink数据 downlink指的是相机传输到host采集卡的高速链路,其中包含了如下类型的数据: 1.Stream Data 2.Trigger Ack, Trigger: 3.Ack ...
- 使用CosmosDB进行大规模数据的实时数据处理和流式传输
目录 使用 Cosmos DB 进行大规模数据的实时数据处理和流式传输 背景介绍 文章目的 目标受众 技术原理及概念 基本概念解释 技术原理介绍 相关技术比较 实现步骤与流程 准备工作:环境配置与依赖 ...
- linux 服务器上如何判断网络是否开通
项目上由于升级了kafka需要测试下网络是否是通的,因此需要使用命令 nc -zv ip地址 端口这个命令来跑一下网络是否是通的,最后发现是新的kafka的config使用了新的端口,没有开通网络 ...
- Linux下NFS服务配置
NFS(Network File System)即网络文件系统,是FreeBSD支持的文件系统中的一种,它允许网络中的计算机之间通过TCP/IP网络共享资源.在NFS的应用中,本地NFS的客户端应用可 ...
- 2023-06-29:redis中什么是热点Key?该如何解决?
2023-06-29:redis中什么是热点Key?该如何解决? 答案2023-06-29: 在Redis中,经常被访问的key被称为热点key. 产生原因和危害 原因 热点key问题产生的原因可以归 ...
- 「学习笔记」CDQ分治
CDQ 分治的思想最早由 IOI2008 金牌得主陈丹琦在高中时整理并总结,目前这个思想的拓展十分广泛. 优点:可以将数据结构或者 DP 优化掉一维 缺点:这是离线算法. 引入 让我们来看一个问题 有 ...
- Spring Boot 日志文件
Spring Boot 日志文件 日志文件是用于记录系统操作事件的记录文件或文件集合,可分为事件日志和消息日志.具有处理历史数据.诊断问题的追踪以及理解系统的活动等重要作用. 事件日志记录系统的执行中 ...
- 详解nvim内建LSP体系与基于nvim-cmp的代码补全体系
2023年,nvim以及其生态已经发展的愈来愈完善了.nvim内置的LSP(以及具体的语言服务)加上众多插件,可以搭建出支持各种类型语法检查.代码补全.代码格式化等功能的IDE.网络上关于如何配置的文 ...