-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
112 lines (78 loc) · 2.93 KB
/
main.py
File metadata and controls
112 lines (78 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import json
import mysql.connector as sql
import logging
from telegram import Update
from telegram.ext import filters, MessageHandler, ApplicationBuilder, CommandHandler, ContextTypes
from openai import OpenAI
def main():
print("Initializing Telegram GPT Parsing to SQL Database...")
openaikey,telegrambotkey, dbsecrets = gatherSecrets()
global instructions
instructions = '"""' + gatherInstructions() + '"""'
global connection
connection = connectToDatase(dbsecrets)
global GPT
GPT = OpenAI(api_key=openaikey)
initiateBot(telegrambotkey)
# Fetching the API keys and Database Secrets
def gatherSecrets():
with open("secrets.json", "r") as file:
secrets = json.load(file)
openaikey = secrets['openaikey']
telegrambotkey = secrets['telegramkey']
dbsecrets = secrets['dbsecrets']
print("Gathering secret keys and database secrets...")
return [openaikey, telegrambotkey, dbsecrets]
def gatherInstructions():
with open("instructions.txt", "r") as file:
instructions = file.read()
print("Gathering instructions for GPT...")
return instructions
# DATABASE and SQL
def connectToDatase(dbsecrets):
print("Connecting to Database...")
try:
connection = sql.connect(
host=dbsecrets['host'],
port=dbsecrets['port'],
user=dbsecrets['user'],
password=dbsecrets['password'],
database=dbsecrets['database']
)
if connection.is_connected():
print("Successfully connected to the database!")
except sql.Error as e:
print(f"Error: {e}")
return connection
def saveToDatabase(query):
try:
cursor = connection.cursor()
cursor.execute(query)
connection.commit()
print("Successfully saved to the database!")
except sql.Error as e:
print(f"Error: {e}")
# TELEGRAM BOT
def initiateBot(telegrambotkey):
print("Initializing Telegram Bot...")
application = ApplicationBuilder().token(telegrambotkey).build()
chat_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), chat)
application.add_handler(chat_handler)
print("Bot is ready to chat, send the message to the bot to get the response...")
application.run_polling()
# Chat Handler
async def chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
completion = GPT.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": instructions},
{"role": "user", "content": update.message.text}
]
)
resulting_message = completion.choices[0].message.content
print("The following message was sent to the bot: \n" + update.message.text + "\n \n")
print("Bot's SQL response: \n" + resulting_message + "\n")
saveToDatabase(resulting_message)
await context.bot.send_message(chat_id=update.effective_chat.id, text=resulting_message)
if __name__ == "__main__":
main()