Skip to content

Commit f59d9bb

Browse files
committed
refactor: refactor file structure
1 parent a4c4514 commit f59d9bb

File tree

3 files changed

+108
-104
lines changed

3 files changed

+108
-104
lines changed

lambda_function.py

+1-104
Original file line numberDiff line numberDiff line change
@@ -1,109 +1,6 @@
11
import json
2-
import os
3-
import urllib3
4-
import random
5-
import openai
6-
7-
BOT_ID = int(os.environ.get('BOT_ID'))
8-
TELEGRAM_TOKEN = os.environ.get('TELEGRAM_TOKEN')
9-
FREQUENCY = float(os.environ.get('FREQUENCY'))
10-
ALLOWED_CHATS = [int(num) for num in os.environ.get('ALLOWED_CHATS').split(',')]
11-
12-
OPENAI_KEY = os.environ.get('OPENAI_KEY')
13-
OPENAI_MODEL = os.environ.get('OPENAI_MODEL')
14-
15-
SEND_MESSAGE_URL = 'https://api.telegram.org/bot' + TELEGRAM_TOKEN + '/sendMessage'
16-
http = urllib3.PoolManager()
17-
18-
class openaiClient:
19-
def __init__(self) -> None:
20-
openai.api_key = OPENAI_KEY
21-
22-
def complete_chat(self, user_message: str):
23-
response = openai.ChatCompletion.create(
24-
model=OPENAI_MODEL,
25-
messages = [
26-
{"role": "system", "content": "Ты чат-бот с открытым исходным кодом, который использует OpenAI GPT-3.5 для генерации ответов на вопросы. Пиши краткие сообщения."},
27-
{"role": "user", "content": user_message},
28-
],
29-
temperature=1.0,
30-
max_tokens=128,
31-
frequency_penalty=1.0,
32-
presence_penalty=1.0,
33-
)
34-
answer = response["choices"][0]["message"]["content"]
35-
print(answer)
36-
return answer
37-
38-
39-
class telegramClient:
40-
def __init__(self) -> None:
41-
self.openai_client = openaiClient()
42-
43-
def send_message(self, text: str, chat_id, original_message_id):
44-
""" Reply to a message of a user
45-
46-
Args:
47-
text (str): the bot's message
48-
chat_id (int): id of a chat
49-
original_message_id (int): id of a message to reply to
50-
"""
51-
payload = {
52-
"chat_id": chat_id,
53-
"parse_mode": "HTML",
54-
"text": text,
55-
"reply_to_message_id": original_message_id
56-
}
57-
response = http.request('POST', SEND_MESSAGE_URL,
58-
headers={'Content-Type': 'application/json'},
59-
body=json.dumps(payload), timeout=10)
60-
print(response.data)
61-
62-
def should_reply(self, message:dict):
63-
""" The function that decides whether the bot should reply to a message or not
64-
65-
Returns:
66-
bool: boolean value
67-
"""
68-
if "reply_to_message" in message and message["reply_to_message"]["from"]["id"] == BOT_ID:
69-
return True
70-
else:
71-
bet = random.random()
72-
if bet < FREQUENCY:
73-
return True
74-
return False
75-
76-
def process_message(self, body):
77-
""" Process a message of a user and with some probability reply to it
78-
79-
Args:
80-
body (str): a telegram webhook body
81-
"""
82-
if (
83-
"message" in body and
84-
not body["message"]["from"]["is_bot"] and
85-
"forward_from_message_id" not in body["message"]
86-
):
87-
message = body["message"]
88-
# Extract the message of a user
89-
if "text" in body["message"]:
90-
user_message = message["text"]
91-
elif "sticker" in body["message"] and "emoji" in body["message"]["sticker"]:
92-
user_message = message["sticker"]["emoji"]
93-
elif "photo" in body["message"] and "caption" in body["message"]:
94-
user_message = message["caption"]
95-
else:
96-
return
97-
98-
chat_id = message["chat"]["id"]
99-
message_id=message["message_id"]
100-
if chat_id not in ALLOWED_CHATS:
101-
return
102-
103-
if self.should_reply(message):
104-
bot_message = self.openai_client.complete_chat(user_message)
105-
self.send_message(bot_message, chat_id, message_id)
1062

3+
from telegram_client import telegramClient
1074

1085
telegram_client = telegramClient()
1096

openai_client.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import os
2+
import openai
3+
4+
OPENAI_KEY = os.environ.get('OPENAI_KEY')
5+
OPENAI_MODEL = os.environ.get('OPENAI_MODEL')
6+
7+
class openaiClient:
8+
def __init__(self) -> None:
9+
openai.api_key = OPENAI_KEY
10+
11+
def complete_chat(self, user_message: str):
12+
response = openai.ChatCompletion.create(
13+
model=OPENAI_MODEL,
14+
messages = [
15+
{"role": "system", "content": "Ты чат-бот с открытым исходным кодом, который использует OpenAI GPT-3.5 для генерации ответов на вопросы. Пиши краткие сообщения."},
16+
{"role": "user", "content": user_message},
17+
],
18+
temperature=1.0,
19+
max_tokens=128,
20+
frequency_penalty=1.0,
21+
presence_penalty=1.0,
22+
)
23+
answer = response["choices"][0]["message"]["content"]
24+
print(answer)
25+
return answer

telegram_client.py

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import json
2+
import os
3+
import urllib3
4+
import random
5+
6+
from openai_client import openaiClient
7+
8+
BOT_ID = int(os.environ.get('BOT_ID'))
9+
TELEGRAM_TOKEN = os.environ.get('TELEGRAM_TOKEN')
10+
FREQUENCY = float(os.environ.get('FREQUENCY'))
11+
ALLOWED_CHATS = [int(num) for num in os.environ.get('ALLOWED_CHATS').split(',')]
12+
13+
SEND_MESSAGE_URL = 'https://api.telegram.org/bot' + TELEGRAM_TOKEN + '/sendMessage'
14+
http = urllib3.PoolManager()
15+
16+
class telegramClient:
17+
def __init__(self) -> None:
18+
self.openai_client = openaiClient()
19+
20+
def send_message(self, text: str, chat_id, original_message_id):
21+
""" Reply to a message of a user
22+
23+
Args:
24+
text (str): the bot's message
25+
chat_id (int): id of a chat
26+
original_message_id (int): id of a message to reply to
27+
"""
28+
payload = {
29+
"chat_id": chat_id,
30+
"parse_mode": "HTML",
31+
"text": text,
32+
"reply_to_message_id": original_message_id
33+
}
34+
response = http.request('POST', SEND_MESSAGE_URL,
35+
headers={'Content-Type': 'application/json'},
36+
body=json.dumps(payload), timeout=10)
37+
print(response.data)
38+
39+
def should_reply(self, message:dict):
40+
""" The function that decides whether the bot should reply to a message or not
41+
42+
Returns:
43+
bool: boolean value
44+
"""
45+
if "reply_to_message" in message and message["reply_to_message"]["from"]["id"] == BOT_ID:
46+
return True
47+
else:
48+
bet = random.random()
49+
if bet < FREQUENCY:
50+
return True
51+
return False
52+
53+
def process_message(self, body):
54+
""" Process a message of a user and with some probability reply to it
55+
56+
Args:
57+
body (str): a telegram webhook body
58+
"""
59+
if (
60+
"message" in body and
61+
not body["message"]["from"]["is_bot"] and
62+
"forward_from_message_id" not in body["message"]
63+
):
64+
message = body["message"]
65+
# Extract the message of a user
66+
if "text" in body["message"]:
67+
user_message = message["text"]
68+
elif "sticker" in body["message"] and "emoji" in body["message"]["sticker"]:
69+
user_message = message["sticker"]["emoji"]
70+
elif "photo" in body["message"] and "caption" in body["message"]:
71+
user_message = message["caption"]
72+
else:
73+
return
74+
75+
chat_id = message["chat"]["id"]
76+
message_id=message["message_id"]
77+
if chat_id not in ALLOWED_CHATS:
78+
return
79+
80+
if self.should_reply(message):
81+
bot_message = self.openai_client.complete_chat(user_message)
82+
self.send_message(bot_message, chat_id, message_id)

0 commit comments

Comments
 (0)