Skip to content

Commit 35ca4d9

Browse files
committed
Add logging, UrlTask and GenericTask
1 parent 8d0f66b commit 35ca4d9

File tree

7 files changed

+132
-17
lines changed

7 files changed

+132
-17
lines changed

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
setup(
44
name='telegram-task-bot',
5-
version='0.0.9',
5+
version='0.0.10',
66
license='BSD-3',
77
description='rpi-radio-alarm library',
88
long_description=open('README.md').read(),

telegramtaskbot/Bot.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import json
2-
import logging
2+
import logging.config
33
import os
44
from typing import List
55

@@ -8,16 +8,15 @@
88
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
99
from telegram.ext import Updater, CommandHandler, Filters, CallbackQueryHandler
1010

11-
logging.basicConfig(filename='telegramTaskBot.log', filemode='a',
12-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
13-
level=logging.INFO)
11+
from telegramtaskbot.Tasks.UrlTask import UrlTask
1412

1513

1614
class TelegramTaskBot(object):
1715
jobs: List[telegram.ext.Job] = []
1816
default_button_list: List[InlineKeyboardButton] = []
1917
cmd_fun = {}
2018
job_names = {}
19+
logger = logging.getLogger(__name__)
2120

2221
def __init__(self, tasks: []):
2322
load_dotenv()
@@ -34,6 +33,8 @@ def __init__(self, tasks: []):
3433
self.cmd_fun[task.job_stop_name] = task.stop
3534
self.default_button_list.extend(task.get_inline_keyboard())
3635
if task.generic:
36+
if isinstance(task, UrlTask):
37+
self.cmd_fun[task.job_actual_value] = task.get_actual_value
3738
self.dispatcher.add_handler(CommandHandler(task.job_start_name, task.start_command, default_filter))
3839
self.dispatcher.add_handler(CommandHandler(task.job_stop_name, task.stop_command, default_filter))
3940

@@ -50,7 +51,7 @@ def get_default_filter():
5051
return default_filter
5152

5253
def start(self, update, context):
53-
reply_markup = InlineKeyboardMarkup(self.build_menu(self.default_button_list, n_cols=2))
54+
reply_markup = InlineKeyboardMarkup(self.build_menu(self.default_button_list, n_cols=1))
5455
context.bot.send_message(chat_id=update.effective_chat.id, text=os.getenv('START_MESSAGE'),
5556
reply_markup=reply_markup)
5657

@@ -61,7 +62,7 @@ def handle_button(self, update, context):
6162
query = update.callback_query
6263
self.cmd_fun.get(query.data)(self.jobs, update, context)
6364
self.save_to_json()
64-
logging.info('after save')
65+
self.logger.info('after save')
6566

6667
def load_from_json(self):
6768
try:
@@ -71,9 +72,9 @@ def load_from_json(self):
7172
for task in self.TASKS:
7273
if task.job_name == job['name']:
7374
task._start(self.jobs, self.updater.job_queue, job['context'])
74-
logging.info(f'Loaded {len(data["jobs"])} from JSON')
75+
self.logger.info(f'Loaded {len(data["jobs"])} from JSON')
7576
except IOError:
76-
logging.info("File not accessible")
77+
self.logger.info("File not accessible")
7778

7879
def save_to_json(self):
7980
data = {'jobs': []}

telegramtaskbot/Tasks/GenericTask.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
from abc import abstractmethod
2+
from typing import List
3+
4+
import telegram
5+
from telegram.ext import JobQueue
6+
7+
from telegramtaskbot.Tasks.Task import Task
8+
9+
10+
class GenericTask(Task):
11+
job_actual_value: str
12+
generic = True
13+
show_subscribe_buttons = False
14+
15+
def __init__(self, job_queue: JobQueue = None):
16+
super().__init__()
17+
self.job_actual_value = 'actual_' + self.job_name
18+
19+
@abstractmethod
20+
def callback(self, context: telegram.ext.CallbackContext):
21+
pass
22+
23+
def start(self, jobs: List[telegram.ext.Job], update: telegram.Update, context: telegram.ext.CallbackContext):
24+
self.handle_start(context, update.callback_query.message.chat_id)
25+
26+
def start_command(self, update: telegram.Update, context: telegram.ext.CallbackContext):
27+
self.handle_start(context, update.message.chat_id)
28+
29+
def handle_start(self, context: telegram.ext.CallbackContext, chat_id: str):
30+
context.bot.send_message(chat_id=chat_id,
31+
text=f'Thank you for subscribing')
32+
self.save_user(chat_id)
33+
self.logger.debug(f'User {chat_id} subscribed')
34+
35+
def stop(self, jobs: List[telegram.ext.Job], update: telegram.Update, context: telegram.ext.CallbackContext):
36+
self.handle_stop(context, update.callback_query.message.chat_id)
37+
38+
def stop_command(self, update: telegram.Update, context: telegram.ext.CallbackContext):
39+
self.handle_stop(context, update.message.chat_id)
40+
41+
def handle_stop(self, context: telegram.ext.CallbackContext, chat_id: str):
42+
users = self.load_users()
43+
users.remove(chat_id)
44+
self.save_to_json(users)
45+
self.logger.debug(f'User {chat_id} unsubscribed')
46+
context.bot.send_message(chat_id=chat_id, text=f'You succesfully unsubscribed')

telegramtaskbot/Task.py renamed to telegramtaskbot/Tasks/Task.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import json
22
import logging
3+
34
from abc import abstractmethod
45
from datetime import timedelta
56
from typing import List
@@ -13,24 +14,27 @@ class Task(object):
1314
job_name: str
1415
job_start_name: str
1516
job_stop_name: str
17+
disable_notifications: bool = True
1618
generic: bool = False # defines if the task looks the same for each user
1719
first_time = 0
1820
repeat_time: timedelta = timedelta(seconds=5)
1921
filename: str = ''
22+
logger = logging.getLogger(__name__)
2023

21-
def __init__(self, job_queue: JobQueue):
22-
pass
24+
def __init__(self, job_queue: JobQueue = None):
25+
self.job_start_name = 'start_' + self.job_name
26+
self.job_stop_name = 'stop_' + self.job_name
2327

2428
def start(self, jobs: List[telegram.ext.Job], update: telegram.Update, context: telegram.ext.CallbackContext):
2529
context.bot.send_message(chat_id=update.callback_query.message.chat_id,
2630
text=f'Setting the job {self.job_name} up')
2731
self._start(jobs, context.job_queue, update.callback_query.message.chat_id)
2832

2933
def start_command(self, update: telegram.Update, context: telegram.ext.CallbackContext):
30-
raise NotImplementedError
34+
pass
3135

3236
def stop_command(self, update: telegram.Update, context: telegram.ext.CallbackContext):
33-
raise NotImplementedError
37+
pass
3438

3539
def _start(self, jobs: List[telegram.ext.Job], job_queue: JobQueue, chat_id):
3640
new_job = job_queue.run_repeating(self.callback, self.repeat_time, context=chat_id, first=self.first_time)
@@ -47,7 +51,7 @@ def stop(self, jobs: List[telegram.ext.Job], update: telegram.Update, context: t
4751
count += 1
4852
idx = jobs.index(job_to_stop)
4953
jobs.pop(idx)
50-
logging.info(f' stopped {count} of {num_jobs} jobs for chat_id={chat_id}')
54+
self.logger.info(f' stopped {count} of {num_jobs} jobs for chat_id={chat_id}')
5155

5256
@abstractmethod
5357
def callback(self, context: telegram.ext.CallbackContext):
@@ -68,7 +72,7 @@ def save_to_json(self, users):
6872
data = {'users': users}
6973
with open(self.filename + '.json', 'w') as outfile:
7074
json.dump(data, outfile)
71-
logging.info('Saved User')
75+
self.logger.debug('Saved User')
7276

7377
def load_users(self):
7478
try:
@@ -77,6 +81,6 @@ def load_users(self):
7781
users = data['users']
7882
except IOError:
7983
users = []
80-
logging.info("File not accessible")
84+
self.logger.error("File not accessible")
8185
finally:
8286
return users

telegramtaskbot/Tasks/UrlTask.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import time as timer
2+
from abc import abstractmethod
3+
4+
import requests
5+
import telegram
6+
from requests import Response
7+
from telegram import InlineKeyboardButton
8+
9+
from telegramtaskbot.Tasks.GenericTask import GenericTask
10+
11+
12+
class UrlTask(GenericTask):
13+
disable_notifications = True
14+
url: str
15+
16+
def callback(self, context: telegram.ext.CallbackContext):
17+
self.logger.info(f'Run {self.job_name}')
18+
users = self.load_users()
19+
response_message = self.get_data()
20+
self.logger.info(f'Notifying {len(users)} users for {self.job_name}')
21+
for user in users:
22+
context.bot.send_message(chat_id=user, text=response_message,
23+
disable_notification=self.disable_notifications)
24+
25+
def get_actual_value(self, joblist: [], update: telegram.Update, context: telegram.ext.CallbackContext):
26+
self.logger.debug(f'Get actual value from {self.job_name} for {update.callback_query.message.chat_id}')
27+
data: str = self.get_data()
28+
context.bot.send_message(chat_id=update.callback_query.message.chat_id, text=data)
29+
self.logger.debug(
30+
f'Send message to {update.callback_query.message.chat_id} with content: \"{" ".join(data.splitlines())}\"')
31+
32+
def get_data(self):
33+
return self.handle_response(self.get_response())
34+
35+
@abstractmethod
36+
def handle_response(self, response: Response):
37+
pass
38+
39+
def get_response(self):
40+
count = 0
41+
response = requests.get(self.url)
42+
if response.status_code != 200:
43+
while response.status_code != 200:
44+
timer.sleep(2)
45+
resp = requests.get(self.url)
46+
count += 1
47+
response = resp
48+
self.logger.debug(f'{self.job_name} tried for {count} times')
49+
return response
50+
51+
def get_inline_keyboard(self):
52+
buttons = [
53+
InlineKeyboardButton(f"Get actual Value for {self.job_name}", callback_data=self.job_actual_value),
54+
]
55+
if self.show_subscribe_buttons:
56+
buttons.append(InlineKeyboardButton(f"Subscribe for {self.job_name}", callback_data=self.job_start_name))
57+
buttons.append(InlineKeyboardButton(f"Unsubscribe for {self.job_name}", callback_data=self.job_stop_name))
58+
return buttons

telegramtaskbot/Tasks/__init__.py

Whitespace-only changes.

telegramtaskbot/__init__.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
1-
from .Task import Task
1+
import logging
2+
23
from .Bot import TelegramTaskBot
4+
from .Tasks.GenericTask import GenericTask
5+
from .Tasks.Task import Task
6+
from .Tasks.UrlTask import UrlTask
7+
8+
logging.getLogger(__name__).addHandler(logging.NullHandler())

0 commit comments

Comments
 (0)