├── README.md
├── config.ini
├── script_mysql.py
└── sessions
└── .gitkeep
/README.md:
--------------------------------------------------------------------------------
1 | # Telegram Bot with MySQL Database
2 |
3 | This project is a Telegram bot that is connected to a MySQL database. The bot allows users to perform various actions on the database, such as inserting, updating, and retrieving data.
4 |
5 | APP_ID and API_HASH for telethon: https://my.telegram.org/auth
6 |
7 | BOT_TOKEN: Write on telegram to @BotFather and follow the instruction
8 |
--------------------------------------------------------------------------------
/config.ini:
--------------------------------------------------------------------------------
1 | ; DO NOT TOUCH [default] !!!
2 | [default]
3 |
4 | ; Editable Fields:
5 |
6 | ; APP_ID and API_HASH for telethon: https://my.telegram.org/auth
7 | api_id =
8 | api_hash =
9 |
10 | ; BOT_TOKEN: Write on telegram to @BotFather and follow the instruction
11 | bot_token =
12 |
13 | ; Check the inside the config.inc.php file
14 | hostname =
15 | username =
16 | password =
17 | ; Give the name you want!
18 | database =
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/script_mysql.py:
--------------------------------------------------------------------------------
1 | ### Importing necessary libraries
2 |
3 | import configparser # pip install configparser
4 | from telethon import TelegramClient, events # pip install telethon
5 | from datetime import datetime
6 | import MySQLdb # pip install mysqlclient
7 |
8 | ### Initializing Configuration
9 | print("Initializing configuration...")
10 | config = configparser.ConfigParser()
11 | config.read('config.ini')
12 |
13 | # Read values for Telethon and set session name
14 | API_ID = config.get('default','api_id')
15 | API_HASH = config.get('default','api_hash')
16 | BOT_TOKEN = config.get('default','bot_token')
17 | session_name = "sessions/Bot"
18 |
19 | # Read values for MySQLdb
20 | HOSTNAME = config.get('default','hostname')
21 | USERNAME = config.get('default','username')
22 | PASSWORD = config.get('default','password')
23 | DATABASE = config.get('default','database')
24 |
25 | # Start the Client (telethon)
26 | client = TelegramClient(session_name, API_ID, API_HASH).start(bot_token=BOT_TOKEN)
27 |
28 |
29 | ### START COMMAND
30 | @client.on(events.NewMessage(pattern="(?i)/start"))
31 | async def start(event):
32 | # Get sender
33 | sender = await event.get_sender()
34 | SENDER = sender.id
35 |
36 | # set text and send message
37 | text = "Hello i am a bot that can do CRUD operations inside a MySQL database"
38 | await client.send_message(SENDER, text)
39 |
40 |
41 | ### Insert command
42 | @client.on(events.NewMessage(pattern="(?i)/insert"))
43 | async def insert(event):
44 | try:
45 | # Get the sender of the message
46 | sender = await event.get_sender()
47 | SENDER = sender.id
48 |
49 | # /insert bottle 10
50 |
51 | # Get the text of the user AFTER the /insert command and convert it to a list (we are splitting by the SPACE " " simbol)
52 | list_of_words = event.message.text.split(" ")
53 | product = list_of_words[1] # the second (1) item is the product
54 | quantity = list_of_words[2] # the third (2) item is the quantity
55 | dt_string = datetime.now().strftime("%d/%m/%Y") # Use the datetime library to the get the date (and format it as DAY/MONTH/YEAR)
56 |
57 | # Create the tuple "params" with all the parameters inserted by the user
58 | params = (product, quantity, dt_string)
59 | sql_command = "INSERT INTO orders VALUES (NULL, %s, %s, %s);" # the initial NULL is for the AUTOINCREMENT id inside the table
60 | crsr.execute(sql_command, params) # Execute the query
61 | conn.commit() # commit the changes
62 |
63 | # If at least 1 row is affected by the query we send specific messages
64 | if crsr.rowcount < 1:
65 | text = "Something went wrong, please try again"
66 | await client.send_message(SENDER, text, parse_mode='html')
67 | else:
68 | text = "Order correctly inserted"
69 | await client.send_message(SENDER, text, parse_mode='html')
70 |
71 | except Exception as e:
72 | print(e)
73 | await client.send_message(SENDER, "Something Wrong happened... Check your code!", parse_mode='html')
74 | return
75 |
76 |
77 |
78 | # Function that creates a message containing a list of all the oders
79 | def create_message_select_query(ans):
80 | text = ""
81 | for i in ans:
82 | id = i[0]
83 | product = i[1]
84 | quantity = i[2]
85 | creation_date = i[3]
86 | text += ""+ str(id) +" | " + ""+ str(product) +" | " + ""+ str(quantity)+" | " + ""+ str(creation_date)+"\n"
87 | message = "Received 📖 Information about orders:\n\n"+text
88 | return message
89 |
90 | ### SELECT COMMAND
91 | @client.on(events.NewMessage(pattern="(?i)/select"))
92 | async def select(event):
93 | try:
94 | # Get the sender of the message
95 | sender = await event.get_sender()
96 | SENDER = sender.id
97 | # Execute the query and get all (*) the oders
98 | crsr.execute("SELECT * FROM orders")
99 | res = crsr.fetchall() # fetch all the results
100 | # If there is at least 1 row selected, print a message with the list of all the oders
101 | # The message is created using the function defined above
102 | if(res):
103 | text = create_message_select_query(res)
104 | await client.send_message(SENDER, text, parse_mode='html')
105 | # Otherwhise, print a default text
106 | else:
107 | text = "No orders found inside the database."
108 | await client.send_message(SENDER, text, parse_mode='html')
109 |
110 | except Exception as e:
111 | print(e)
112 | await client.send_message(SENDER, "Something Wrong happened... Check your code!", parse_mode='html')
113 | return
114 |
115 |
116 |
117 | ### UPDATE COMMAND
118 | @client.on(events.NewMessage(pattern="(?i)/update"))
119 | async def update(event):
120 | try:
121 | # Get the sender
122 | sender = await event.get_sender()
123 | SENDER = sender.id
124 |
125 | # Get the text of the user AFTER the /update command and convert it to a list (we are splitting by the SPACE " " simbol)
126 | list_of_words = event.message.text.split(" ")
127 | id = int(list_of_words[1]) # second (1) item is the id
128 | new_product = list_of_words[2] # third (2) item is the product
129 | new_quantity = list_of_words[3] # fourth (3) item is the quantity
130 | dt_string = datetime.now().strftime("%d/%m/%Y") # We create the new date
131 |
132 | # create the tuple with all the params interted by the user
133 | params = (id, new_product, new_quantity, dt_string, id)
134 |
135 | # Create the UPDATE query, we are updating the product with a specific id so we must put the WHERE clause
136 | sql_command="UPDATE orders SET id=%s, product=%s, quantity=%s, LAST_EDIT=%s WHERE id =%s"
137 | crsr.execute(sql_command, params) # Execute the query
138 | conn.commit() # Commit the changes
139 |
140 | # If at least 1 row is affected by the query we send a specific message
141 | if crsr.rowcount < 1:
142 | text = "Order with id {} is not present".format(id)
143 | await client.send_message(SENDER, text, parse_mode='html')
144 | else:
145 | text = "Order with id {} correctly updated".format(id)
146 | await client.send_message(SENDER, text, parse_mode='html')
147 |
148 | except Exception as e:
149 | print(e)
150 | await client.send_message(SENDER, "Something Wrong happened... Check your code!", parse_mode='html')
151 | return
152 |
153 |
154 |
155 | @client.on(events.NewMessage(pattern="(?i)/delete"))
156 | async def delete(event):
157 | try:
158 | # Get the sender
159 | sender = await event.get_sender()
160 | SENDER = sender.id
161 |
162 | #/ delete 1
163 |
164 | # get list of words inserted by the user
165 | list_of_words = event.message.text.split(" ")
166 | id = list_of_words[1] # The second (1) element is the id
167 |
168 | # Crete the DELETE query passing the id as a parameter
169 | sql_command = "DELETE FROM orders WHERE id = (%s);"
170 |
171 | # ans here will be the number of rows affected by the delete
172 | ans = crsr.execute(sql_command, (id,))
173 | conn.commit()
174 |
175 | # If at least 1 row is affected by the query we send a specific message
176 | if ans < 1:
177 | text = "Order with id {} is not present".format(id)
178 | await client.send_message(SENDER, text, parse_mode='html')
179 | else:
180 | text = "Order with id {} was correctly deleted".format(id)
181 | await client.send_message(SENDER, text, parse_mode='html')
182 |
183 | except Exception as e:
184 | print(e)
185 | await client.send_message(SENDER, "Something Wrong happened... Check your code!", parse_mode='html')
186 | return
187 |
188 |
189 |
190 | # Create database function
191 | def create_database(query):
192 | try:
193 | crsr_mysql.execute(query)
194 | print("Database created successfully")
195 | except Exception as e:
196 | print(f"WARNING: '{e}'")
197 |
198 | ##### MAIN
199 | if __name__ == '__main__':
200 | try:
201 | print("Initializing Database...")
202 | conn_mysql = MySQLdb.connect( host=HOSTNAME, user=USERNAME, passwd=PASSWORD )
203 | crsr_mysql = conn_mysql.cursor()
204 |
205 | query = "CREATE DATABASE "+str(DATABASE)
206 | create_database(query)
207 | conn = MySQLdb.connect( host=HOSTNAME, user=USERNAME, passwd=PASSWORD, db=DATABASE )
208 | crsr = conn.cursor()
209 |
210 | # Command that creates the "oders" table
211 | sql_command = """CREATE TABLE IF NOT EXISTS orders (
212 | id INTEGER PRIMARY KEY AUTO_INCREMENT,
213 | product VARCHAR(200),
214 | quantity INT(10),
215 | LAST_EDIT VARCHAR(100));"""
216 |
217 | crsr.execute(sql_command)
218 | print("All tables are ready")
219 |
220 | print("Bot Started...")
221 | client.run_until_disconnected()
222 |
223 | except Exception as error:
224 | print('Cause: {}'.format(error))
--------------------------------------------------------------------------------
/sessions/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Raiseku/Telegram-Bot-MYSQL-Database/4b6281b39d9f6b23ae74297e42eac2e76a7280c4/sessions/.gitkeep
--------------------------------------------------------------------------------