Skip to content

Commit 259ec84

Browse files
authored
Clean up code (#19)
* fix missing variable * clean up code, switch to f-strings
1 parent 731f8ba commit 259ec84

7 files changed

Lines changed: 39 additions & 62 deletions

File tree

source-code/chapter-3/python-app/LICENSE

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
The MIT License (MIT)
22

3-
Copyright (c) 2015 Sathya
3+
Copyright (c) 2015 Sathyajith Bhat
44

55
Permission is hereby granted, free of charge, to any person obtaining a copy
66
of this software and associated documentation files (the "Software"), to deal

source-code/chapter-3/python-app/README.md

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,16 @@ Refer to the [book repo](https://github.com/apress/practical-docker-with-python)
66

77
### Getting started
88

9-
Install the requirements with pip
9+
- Clone the repo or download the code
10+
- Install the requirements with pip
1011

1112
pip3 install -r requirements.txt
1213

13-
Start the bot
14-
15-
NBT_ACCESS_TOKEN=<token> python newsbot.py
14+
- Set the environment variable `NBT_ACCESS_TOKEN` where the value is the Bot token generated using Telegram BotFather.
15+
- See instructions on how to generate the token in Chapter 3 or [refer to this guide](https://core.telegram.org/bots/api#authorizing-your-bot)
16+
- See this guide on [how to set environment variables](https://core.telegram.org/bots/api#authorizing-your-bot)
17+
- Start the bot
18+
python newsbot.py
1619

1720
where `<token>` is the [Telegram Bot API](https://core.telegram.org/bots/api) token
1821

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
__author__ = 'Sathyajith'
22

3-
import os
3+
from os import environ
4+
from sys import exit
45
ERR_NO_SOURCE = 'No sources defined! Set a source using /source list, of, sub, reddits'
56
skip_list = []
67
sources_dict = {}
8+
UPDATE_PERIOD = 1
9+
FALSE_RESPONSE = {"ok": False}
710

8-
BOT_KEY = os.environ['NBT_ACCESS_TOKEN']
9-
API_BASE = 'https://api.telegram.org/bot'
10-
UPDATE_PERIOD = 6
11-
FALSE_RESPONSE = {"ok": False}
11+
BOT_KEY = environ.get('NBT_ACCESS_TOKEN')
12+
if not BOT_KEY:
13+
print("Telegram access token not set, exiting.")
14+
exit(1)
15+
API_BASE = f'https://api.telegram.org/bot{BOT_KEY}'

source-code/chapter-3/python-app/main.py

Lines changed: 0 additions & 22 deletions
This file was deleted.

source-code/chapter-3/python-app/newsbot.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,15 @@ def get_last_updated():
1212
f.close()
1313
except FileNotFoundError:
1414
last_updated = 0
15-
log.debug('Last updated id: {0}'.format(last_updated))
15+
log.debug(f"Last updated id: {last_updated}")
1616
return last_updated
1717

1818
if __name__ == '__main__':
1919

2020
try:
21-
log.debug('Starting up')
21+
log.info("Starting up")
2222
States.last_updated = get_last_updated()
2323
while True:
2424
handle_incoming_messages(States.last_updated)
2525
except KeyboardInterrupt:
26-
log.info('Received KeybInterrupt, exiting')
26+
log.info("Received KeybInterrupt, exiting")

source-code/chapter-3/python-app/reddit.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,25 @@
44
__author__ = 'Sathyajith'
55

66

7-
def summarize(url):
8-
log.info('Not yet implemented!')
9-
return url
10-
11-
127
def get_latest_news(sub_reddits):
138
log.debug('Fetching news from reddit')
149
r = praw.Reddit(user_agent='Practical Docker With Python tutorial')
1510
# Can change the subreddit or add more.
1611
sub_reddits = clean_up_subreddits(sub_reddits)
17-
log.debug('Fetching subreddits: {0}'.format(sub_reddits))
12+
log.debug(f"Fetching subreddits: {sub_reddits}")
1813
submissions = r.get_subreddit(sub_reddits).get_top(limit=5)
1914
submission_content = ''
2015
try:
2116
for post in submissions:
22-
submission_content += summarize(post.title + ' - ' + post.url) + '\n'
17+
submission_content += f"{post.title} - {post.url} \n\n"
2318
except praw.errors.Forbidden:
24-
log.debug('subreddit {0} is private'.format(sub_reddits))
19+
log.info(f"subreddit {sub_reddits} is private".format())
2520
submission_content = "Sorry couldn't fetch; subreddit is private"
2621
except praw.errors.InvalidSubreddit:
27-
log.debug('Subreddit {} is invalid or doesn''t exist.'.format(sub_reddits))
22+
log.info(f"Subreddit {sub_reddits} is invalid or doesn''t exist.")
2823
submission_content = "Sorry couldn't fetch; subreddit doesn't seem to exist"
2924
except praw.errors.NotFound :
30-
log.debug('Subreddit {} is invalid or doesn''t exist.'.format(sub_reddits))
25+
log.info(f"Subreddit {sub_reddits} is invalid or doesn''t exist.")
3126
submission_content = "Sorry couldn't fetch; something went wrong, please do send a report to @sathyabhat"
3227
return submission_content
3328

source-code/chapter-3/python-app/telegram.py

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@
1010

1111

1212
def get_updates(last_updated):
13-
log.debug('Checking for requests, last updated passed is: {}'.format(last_updated))
13+
log.debug('Checking for requests, last updated passed is: {last_updated}')
1414
sleep(UPDATE_PERIOD)
15-
response = requests.get(API_BASE + BOT_KEY + '/getUpdates', params={'offset': last_updated+1})
15+
response = requests.get(f"{API_BASE}/getUpdates", params={'offset': last_updated+1})
1616
json_response = FALSE_RESPONSE
1717
if response.status_code != 200:
1818
# wait for a bit, try again
@@ -23,14 +23,14 @@ def get_updates(last_updated):
2323
except ValueError:
2424
sleep(UPDATE_PERIOD*20)
2525
get_updates(last_updated)
26-
log.info('received response: {}'.format(json_response))
26+
log.info(f"received response: {json_response}")
2727
return json_response
2828

2929

3030
def post_message(chat_id, text):
31-
log.info('posting {} to {}'.format(text, chat_id))
31+
log.debug(f"posting {text} to {chat_id}")
3232
payload = {'chat_id': chat_id, 'text': text}
33-
requests.post(API_BASE + BOT_KEY + '/sendMessage', data=payload)
33+
requests.post(f"{API_BASE}/sendMessage", data=payload)
3434

3535

3636
def handle_incoming_messages(last_updated):
@@ -49,26 +49,23 @@ def handle_incoming_messages(last_updated):
4949
chat_text = ''
5050
split_chat_text.append(chat_text)
5151
log.debug('Looks like no chat text was detected... moving on')
52-
try:
53-
if 'message' in req:
54-
person_id = req['message']['from']['id']
55-
else:
56-
person_id = ['edited_message']['from']['id']
57-
except KeyError:
58-
pass
5952

60-
log.info('Chat text received: {0}'.format(chat_text))
53+
if 'message' in req:
54+
person_id = req['message']['from']['id']
55+
else:
56+
person_id = req['edited_message']['from']['id']
57+
58+
log.info(f"Chat text received: {chat_text}")
6159
r = re.search('(source+)(.*)', chat_text)
6260

6361
if (r is not None and r.group(1) == 'source'):
6462
if r.group(2):
6563
sources_dict[person_id] = r.group(2)
66-
log.debug('Sources set for {0} to {1}'.format(sources_dict[person_id], r.group(2)))
67-
post_message(person_id, 'Sources set as {0}!'.format(r.group(2)))
64+
post_message(person_id, f"Sources set as {r.group(2)}!")
6865
else:
6966
post_message(person_id, 'We need a comma separated list of subreddits! No subreddit, no news :-(')
7067
if chat_text == '/stop':
71-
log.debug('Added {0} to skip list'.format(chat_sender_id))
68+
log.debug(f"Added {chat_sender_id} to skip list")
7269
skip_list.append(chat_sender_id)
7370
post_message(chat_sender_id, "Ok, we won't send you any more messages.")
7471

@@ -95,5 +92,5 @@ def handle_incoming_messages(last_updated):
9592
f.write(str(last_updated))
9693
States.last_updated = last_updated
9794
log.debug(
98-
'Updated last_updated to {0}'.format(last_updated))
95+
f'Updated last_updated to {last_updated}')
9996
f.close()

0 commit comments

Comments
 (0)