Skip to content

Commit b7816a0

Browse files
manavmehtaManav Mehta
authored andcommitted
lint and convert to modular server
1 parent bde819d commit b7816a0

File tree

8 files changed

+189
-82
lines changed

8 files changed

+189
-82
lines changed

.github/workflows/pylint.yml

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
name: Pylint
2+
3+
on: [push]
4+
5+
jobs:
6+
build:
7+
runs-on: ubuntu-latest
8+
strategy:
9+
matrix:
10+
python-version: ["3.10"]
11+
steps:
12+
- uses: actions/checkout@v3
13+
- name: Set up Python ${{ matrix.python-version }}
14+
uses: actions/setup-python@v3
15+
with:
16+
python-version: ${{ matrix.python-version }}
17+
- name: Install dependencies
18+
run: |
19+
python -m pip install --upgrade pip
20+
pip install pylint
21+
- name: Analysing the code with pylint
22+
run: |
23+
pylint $(git ls-files '*.py')

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ pip install -r requirements.txt
1717
```python
1818
python app.py
1919
```
20+
2021
# Instructions to add Mallya to your Telegram
2122
* Add Mallya to your Telegram by clicking [this link](https://t.me/MallyaBot)
2223
* Chat with the King of good times

app.py

Lines changed: 61 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,85 @@
11
#!/usr/bin/env python3
2+
"""
3+
primary entry point to the bot backend
4+
"""
25

3-
import threading
6+
import os
47
import time
8+
import signal
9+
import logging
510
from collections import OrderedDict
6-
import os
7-
import telebot
11+
from concurrent.futures import ThreadPoolExecutor
812
import dotenv
13+
import telebot
14+
from telebot.types import Update
915
import utils
1016

17+
# Load environment variables
1118
dotenv.load_dotenv()
1219
TOKEN = os.getenv("TOKEN")
1320

21+
# Initialize the bot
1422
bot = telebot.TeleBot(TOKEN)
1523

24+
# Initialize update ID dictionary and logger
1625
updateid_dict = OrderedDict()
26+
logging.basicConfig(
27+
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
28+
)
29+
30+
# Define maximum threads and updates to fetch
31+
MAX_THREADS = 10
32+
MAX_UPDATES = 100
33+
34+
# Initialize the thread pool
35+
executor = ThreadPoolExecutor(max_workers=MAX_THREADS)
36+
1737

38+
def fetch_updates(offset):
39+
"""
40+
Fetch updates from the Telegram server.
41+
"""
42+
return (
43+
bot.get_updates()
44+
if offset is None
45+
else bot.get_updates(offset, MAX_UPDATES, timeout=20)
46+
)
1847

19-
def index():
48+
49+
def process_update(update: Update):
2050
"""
21-
Main function that is responsible to run the server.
51+
Process an incoming update.
2252
"""
53+
if update.update_id not in updateid_dict:
54+
updateid_dict[update.update_id] = time.time()
55+
try:
56+
executor.submit(utils.address_query, update)
57+
except Exception as exception:
58+
logging.error(
59+
"Unable to process update {%s}: {%s}", update.update_id, exception
60+
)
61+
62+
if len(updateid_dict) > 50:
63+
updateid_dict.popitem(last=False)
2364

65+
66+
def run_bot():
67+
"""
68+
Main function that runs the bot.
69+
"""
70+
logging.info("Bot is starting...")
2471
last_update_id = None
2572

26-
# Keep Listening to incoming requests
2773
while True:
28-
# The following conditional ensures fetching of latest 50 updates
29-
updates_list = None
30-
if last_update_id is None:
31-
updates_list = bot.get_updates()
32-
else:
33-
updates_list = bot.get_updates(last_update_id, 100, 20)
34-
35-
for update in updates_list:
36-
last_update_id = update.update_id
37-
38-
if update.update_id not in updateid_dict.keys():
39-
updateid_dict[update.update_id] = time.time()
40-
try:
41-
new_thread = threading.Thread(
42-
target=utils.address_query, args=(update,)
43-
)
44-
new_thread.start()
45-
except Exception as exception:
46-
print("Unable to create a thread")
47-
raise exception
48-
49-
if len(updateid_dict.keys()) > 50:
50-
updateid_dict.pop(list(updateid_dict.keys())[0])
74+
try:
75+
updates_list = fetch_updates(last_update_id)
76+
for update in updates_list:
77+
last_update_id = update.update_id
78+
process_update(update)
79+
except Exception as e:
80+
logging.error("Error while fetching or processing updates: {%s}", e)
81+
time.sleep(5) # Sleep for a bit before retrying
5182

5283

5384
if __name__ == "__main__":
54-
index()
85+
run_bot()

commands.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
"""
22
default commands for the bot
33
"""
4+
45
commands = {
5-
'start': 'Hello there {}! I am a bot sent by the heavens to be yours. Type /help and know what I can do for you.',
6-
'hi':'Hello there {}!',
7-
'hello':'Hello there {}!',
8-
'hey':'Hello there {}!',
9-
'help': 'Hey, {}. I see you sought my help.\n\nI know the following commands:\n/Hi, /Hey, /Hello - They\'re pretty much the same😬\n/Help - To know how I can help you.\n\n/q followed by your query - regarding IIT Mandi. \ne.g:\n/q What all facilities are available in campus?\n\nFor General questions you can just ask straight-away.\ne.g:\nWhat is your name\nTell me a joke\n\nYou can also use /u, /d and /n to upvote, downvote and get the next answer respectively. These three are only valid when you ask a query.'
6+
"start": "Hello there {}! I am a bot sent by the heavens to be yours. Type /help and know what I can do for you.",
7+
"hi": "Hello there {}!",
8+
"hello": "Hello there {}!",
9+
"hey": "Hello there {}!",
10+
"help": "Hey, {}. I see you sought my help.\n\nI know the following commands:\n/Hi, /Hey, /Hello - They're pretty much the same😬\n/Help - To know how I can help you.\n\n/q followed by your query - regarding IIT Mandi. \ne.g:\n/q What all facilities are available in campus?\n\nFor General questions you can just ask straight-away.\ne.g:\nWhat is your name\nTell me a joke\n\nYou can also use /u, /d and /n to upvote, downvote and get the next answer respectively. These three are only valid when you ask a query.",
1011
}

db.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
"""
2+
program to setup db
3+
"""
4+
15
import os
26
import logging
37
import dotenv
@@ -11,6 +15,7 @@
1115

1216
logger = logging.getLogger(__name__)
1317

18+
1419
def init_db():
1520
"""
1621
Initializes the database client and returns a reference to the database.
@@ -112,12 +117,17 @@ def update_vote_qna(vote_type: str, answer: str):
112117
"""
113118
try:
114119
qna = get_collection(DB, "qna")
115-
where_clause = {'answers.answer': answer}
116-
update_clause = {"$inc": {"answers.$.upvotes": 1}} if vote_type == "u" else {"$inc": {"answers.$.downvotes": 1}}
120+
where_clause = {"answers.answer": answer}
121+
update_clause = (
122+
{"$inc": {"answers.$.upvotes": 1}}
123+
if vote_type == "u"
124+
else {"$inc": {"answers.$.downvotes": 1}}
125+
)
117126
qna.update_one(where_clause, update_clause)
118127
except Exception as exception:
119128
logger.exception("Error updating vote count for answer: %s", answer)
120129
raise exception
121130

131+
122132
global DB
123133
DB = init_db()

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@ pyTelegramBotAPI==4.11.0
33
python-dotenv
44
tensorflow_hub
55
tensorflow
6-
urllib3==1.26.6
6+
urllib3==1.26.18

resources/populateDB.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import sys
2-
sys.path.append('..')
2+
3+
sys.path.append("..")
34
from db import *
45
from pprint import pprint
56

7+
68
def restructureQnA():
79
collection = get_collection(DB, "qna")
810
all_documents = collection.find()
@@ -18,7 +20,11 @@ def restructureQnA():
1820

1921
# if the question is not in the dictionary, add it
2022
if question not in question_answer_dict:
21-
question_answer_dict[question] = {"_id": document["_id"], "question": question, "answers": [answer]}
23+
question_answer_dict[question] = {
24+
"_id": document["_id"],
25+
"question": question,
26+
"answers": [answer],
27+
}
2228
else:
2329
# if the question is already in the dictionary, add the answer to the list of answers
2430
question_answer_dict[question]["answers"].append(answer)
@@ -29,10 +35,15 @@ def restructureQnA():
2935
# update the documents to add upvotes and downvotes to each answer
3036
for document in combined_documents:
3137
for answer_index, answer in enumerate(document["answers"]):
32-
document["answers"][answer_index] = {"answer": answer, "upvotes": 0, "downvotes": 0}
38+
document["answers"][answer_index] = {
39+
"answer": answer,
40+
"upvotes": 0,
41+
"downvotes": 0,
42+
}
3343
pprint(combined_documents)
3444
# insert the updated documents into the collection
3545
collection.delete_many({})
3646
collection.insert_many(combined_documents)
3747

38-
restructureQnA()
48+
49+
restructureQnA()

0 commit comments

Comments
 (0)