├── .gitattributes
├── ChatGPT_bot.py
├── README.md
├── analytics.py
├── bot.py
├── config.json
├── data.csv
├── python_setup.sh
└── requirements.txt
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/ChatGPT_bot.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 |
4 | import openai
5 | import logging
6 | import analytics
7 | import json
8 |
9 | from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
10 |
11 | logging.basicConfig(
12 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
13 | level=logging.INFO
14 | )
15 |
16 |
17 | # Load config.json file
18 | with open('config.json') as f:
19 | config = json.load(f)
20 |
21 | # Set up ChatGPT API client
22 | openai.api_key = config['OpenAItoken']
23 | async def start(update, context: ContextTypes.DEFAULT_TYPE):
24 | await context.bot.send_message(chat_id=update.effective_chat.id, text="Hello! I am a ChatGPT bot. How can I help you today? Just send me a message and I will keep talking.")
25 |
26 | async def statistic(update, context: ContextTypes.DEFAULT_TYPE):
27 | await context.bot.send_message(chat_id=update.effective_chat.id, text=analytics.analysis())
28 |
29 |
30 | async def about(update, context: ContextTypes.DEFAULT_TYPE):
31 | await context.bot.send_message(chat_id=update.effective_chat.id,
32 | text="This is ChatGPT bot which can assist you in different tasks.\
33 | You can ask to translate, rephrase or summarize text. \
34 | You can also ask to create a letter or meeting agenda. \nEnjoy 🙂 \nBy @yuliya_rubtsova\n \n \n\
35 | ChatGPT - это бот, который может помочь вам с различными задачами.\
36 | Вы можете попросить его перевести, перефразировать или обобщить текст, а также создать письмо или повестку дня для встречи.\
37 | \nПриятной работы 🙂 \nВопросы и предложения можете слать автору: @yuliya_rubtsova")
38 |
39 | async def donate(update, context: ContextTypes.DEFAULT_TYPE):
40 |
41 | await context.bot.send_message(chat_id=update.effective_chat.id,
42 | text='Sadly, OpenAI charges money for each request to the ChatGPT model, so if you appreciate the bot, you can help to keep it running\n \n \n\
43 | К сожалению, OpenAI берет деньги за каждый запрос к модели ChatGPT, поэтому, если вы цените бота, вы можете помочь и поддерживать его работу', parse_mode='HTML')
44 |
45 | # Get response from ChatGPT API
46 | async def chat(update, context: ContextTypes.DEFAULT_TYPE):
47 | # Check if message is not None
48 | try:
49 | #if update.message and update.message.text:
50 | # Get user's message
51 | message = update.message.text
52 | # Get statistics
53 | analytics.statistics(update.effective_chat.id)
54 | # Send message to ChatGPT API
55 | response = openai.ChatCompletion.create(
56 | #engine="text-davinci-003",
57 | model="gpt-3.5-turbo",
58 | messages=[
59 | {"role": "user", "content": message}
60 | ]
61 | )
62 |
63 |
64 | # Get response from ChatGPT API
65 | response_text = response["choices"][0]["message"]["content"]
66 |
67 | analytics.statistics(update.effective_chat.id, update.effective_user.username,
68 | update.effective_user.first_name,
69 | update.effective_user.last_name, message, response_text)
70 |
71 | # Send response to user
72 | await context.bot.send_message(chat_id=update.effective_chat.id, text=response_text)
73 |
74 | except:
75 | await context.bot.send_message(chat_id=update.effective_chat.id,
76 | text="The bot's credentials have been depleted. To continue using it, please refill its account. \nSadly, OpenAI charges money for each request to the ChatGPT model, so if you appreciate the bot, you can help to keep it running\n \n \n\
77 | Если вы видете это сообщение, значит у бота закончились деньги. К сожалению, OpenAI берет деньги за каждый запрос к модели ChatGPT, поэтому, если вы цените бота, вы можете помочь и поддерживать его работу",
78 | parse_mode='HTML')
79 |
80 |
81 | if __name__ == '__main__':
82 | application = ApplicationBuilder().token(config['TelegramBotToken']).build()
83 |
84 | start_handler = CommandHandler('start', start)
85 | chat_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), chat)
86 | statistic_handler = CommandHandler('statistic', statistic)
87 | about_handler = CommandHandler('about', about)
88 | donate_handler = CommandHandler('donate', donate)
89 |
90 | application.add_handler(start_handler)
91 | application.add_handler(chat_handler)
92 | application.add_handler(statistic_handler)
93 | application.add_handler(about_handler)
94 | application.add_handler(donate_handler)
95 |
96 | application.run_polling()
97 |
98 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ChatGPT_TelegramBot
2 | ChatGPT bot for Telegram https://t.me/GPToMaticbot
3 |
4 | Easy to use a Telegram ChatBot that utilizes ChatGPT technology.
5 |
6 | ChatGPT by OpenAI is a large language model developed by OpenAI that is designed to generate human-like text. It can be used to perform a variety of tasks, including generating responses to user input, summarizing long pieces of text, and completing partially written sentences or paragraphs. Some possible uses of ChatGPT include creating chatbots, generating content for social media or websites, and assisting with language translation. ChatGPT is trained on a vast amount of text data and can generate responses in a wide range of styles and tones, making it a versatile tool for natural language processing tasks.
7 |
8 | 
9 |
10 | There are two files in the repository with different models:
11 | 1. bot.py with text-davinci-003 generative model
12 | 2. ChatGPT_bot.py with ChatGPT: gpt-3.5-turbo model.
13 |
14 | Be aware that gpt-3.5-turbo uses openai.ChatCompletion.create while text-davinci-003 openai.Completion.create
15 |
--------------------------------------------------------------------------------
/analytics.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 |
4 | import csv
5 | import datetime
6 | import pandas as pd
7 |
8 |
9 | # write data to csv
10 | def statistics(user_id):
11 | data = datetime.datetime.today().strftime("%Y-%m-%d")
12 | with open('data.csv', 'a', newline="") as fil:
13 | wr = csv.writer(fil, delimiter=';')
14 | wr.writerow([data, user_id])
15 |
16 |
17 | # create a report
18 | def analysis():
19 | today = datetime.datetime.today().strftime("%Y-%m-%d")
20 | df = pd.read_csv('data.csv', delimiter=';', encoding='utf8')
21 | df_today = df[df['data'] == today]
22 | number_of_users = len(df['id'].unique())
23 | number_of_requests = len(df.index)
24 | number_of_users_today = len(df_today['id'].unique())
25 | number_of_requests_today = len(df_today.index)
26 |
27 |
28 | # number_of_days = len(df['data'].unique())
29 |
30 | message_to_user = 'Number of requests today: ' + '%s' % number_of_requests_today + '\n' \
31 | + 'Total number of requests: '+ '%s' % number_of_requests + '\n' \
32 | + 'Number of users today: ' + '%s' %number_of_users_today + '\n' \
33 | + 'Total number of users: ' + '%s' %number_of_users
34 |
35 |
36 |
37 | return message_to_user
38 |
39 |
--------------------------------------------------------------------------------
/bot.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 |
4 | import openai
5 | import logging
6 | import analytics
7 | import json
8 |
9 | from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
10 |
11 | logging.basicConfig(
12 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
13 | level=logging.INFO
14 | )
15 |
16 |
17 | # Load config.json file
18 | with open('config.json') as f:
19 | config = json.load(f)
20 |
21 | # Set up ChatGPT API client
22 | openai.api_key = config['OpenAItoken']
23 | async def start(update, context: ContextTypes.DEFAULT_TYPE):
24 | await context.bot.send_message(chat_id=update.effective_chat.id, text="Hello! I am a ChatGPT bot. How can I help you today? Just send me a message and I will keep talking.")
25 |
26 | async def statistic(update, context: ContextTypes.DEFAULT_TYPE):
27 | await context.bot.send_message(chat_id=update.effective_chat.id, text=analytics.analysis())
28 |
29 |
30 | async def about(update, context: ContextTypes.DEFAULT_TYPE):
31 | await context.bot.send_message(chat_id=update.effective_chat.id,
32 | text="This is ChatGPT bot which can assist you in different tasks.\
33 | You can ask to translate, rephrase or summarize text. \
34 | You can also ask to create a letter or meeting agenda. \nEnjoy 🙂 \nBy @yuliya_rubtsova\n \n \n\
35 | ChatGPT - это бот, который может помочь вам с различными задачами.\
36 | Вы можете попросить его перевести, перефразировать или обобщить текст, а также создать письмо или повестку дня для встречи.\
37 | \nПриятной работы 🙂 \nВопросы и предложения можете слать автору: @yuliya_rubtsova")
38 |
39 | async def donate(update, context: ContextTypes.DEFAULT_TYPE):
40 |
41 | await context.bot.send_message(chat_id=update.effective_chat.id,
42 | text='Sadly, OpenAI charges money for each request to the ChatGPT model, so if you appreciate the bot, you can help to keep it running\n \n \n\
43 | К сожалению, OpenAI берет деньги за каждый запрос к модели ChatGPT, поэтому, если вы цените бота, вы можете помочь и поддерживать его работу', parse_mode='HTML')
44 |
45 |
46 | async def chat(update, context: ContextTypes.DEFAULT_TYPE):
47 | # Check if message is not None
48 | if update.message and update.message.text:
49 | # Get user's message
50 | message = update.message.text
51 | # Get statistics
52 | analytics.statistics(update.effective_chat.id)
53 | # Send message to ChatGPT API
54 | response = openai.Completion.create(
55 | #engine="text-davinci-003",
56 | model= "text-davinci-003",
57 | prompt=message,
58 | max_tokens=500,
59 | temperature=0.3
60 | )
61 |
62 | # Get response from ChatGPT API
63 | response_text = response['choices'][0]['text']
64 |
65 | # Send response to user
66 | await context.bot.send_message(chat_id=update.effective_chat.id, text=response_text)
67 |
68 |
69 |
70 | if __name__ == '__main__':
71 | application = ApplicationBuilder().token(config['TelegramBotToken']).build()
72 |
73 | start_handler = CommandHandler('start', start)
74 | chat_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), chat)
75 | statistic_handler = CommandHandler('statistic', statistic)
76 | about_handler = CommandHandler('about', about)
77 | donate_handler = CommandHandler('donate', donate)
78 |
79 | application.add_handler(start_handler)
80 | application.add_handler(chat_handler)
81 | application.add_handler(statistic_handler)
82 | application.add_handler(about_handler)
83 | application.add_handler(donate_handler)
84 |
85 | application.run_polling()
86 |
87 |
--------------------------------------------------------------------------------
/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "OpenAItoken": "your OpenAI token",
3 | "TelegramBotToken": "your telegram bot token"
4 | }
--------------------------------------------------------------------------------
/data.csv:
--------------------------------------------------------------------------------
1 | data;id
--------------------------------------------------------------------------------
/python_setup.sh:
--------------------------------------------------------------------------------
1 | pip install openai python-telegram-bot
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | openai==0.27.0
2 | python-telegram-bot
--------------------------------------------------------------------------------