Skip to content

Commit

Permalink
Add multiple chats, minor improvements and bug fix
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandrebarbaruiva committed Jun 7, 2019
1 parent 0cba349 commit bfb5395
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 45 deletions.
110 changes: 66 additions & 44 deletions dailybot.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import logging
import datetime
import logging
import os
import sys
from configparser import ConfigParser
from time import sleep

import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram.ext import Updater, CommandHandler


class DailyBot:
Expand All @@ -17,7 +15,7 @@ def __init__(self, token):
level=logging.INFO,
)
self.logger = logging.getLogger("LOG")
self.logger.info("Starting bot.")
self.logger.info("Starting BOT.")
self.updater = Updater(token)
self.dispatcher = self.updater.dispatcher

Expand All @@ -26,14 +24,17 @@ def __init__(self, token):
daily_hour = int(os.environ.get("HOUR"))
daily_minute = int(os.environ.get("MINUTE"))
daily_time = datetime.time(hour=daily_hour, minute=daily_minute)
self.job_daily = self.job.run_daily(self.send_daily, time=daily_time, days=(0, 1, 2, 3, 4))
self.job_daily = self.job.run_daily(self.send_daily, time=daily_time, days=(2, 4))

start_handler = CommandHandler("start", self.send_start)
self.dispatcher.add_handler(start_handler)

example_handler = CommandHandler("example", self.send_example)
self.dispatcher.add_handler(example_handler)

daily_handler = CommandHandler("daily", self.send_daily)
self.dispatcher.add_handler(daily_handler)

self.dispatcher.add_error_handler(self.error)

@staticmethod
Expand All @@ -49,53 +50,74 @@ def send_type_action(chatbot, update):
def send_start(self, chatbot, update):
"""
Start command to receive /start message on Telegram.
@bot = information about the bot
@BOT = information about the BOT
@update = the user info.
"""
chat_id = os.environ.get("CHAT_ID")
self.logger.info("Start command received.")
self.logger.info(f"{update}")
self.send_type_action(chatbot, update)
name = update.message["chat"]["first_name"]

with open("start.md") \
as start_file:
start_text = start_file.read()
chatbot.send_message(
chat_id=chat_id,
text=start_text,
parse_mode=telegram.ParseMode.MARKDOWN,
)
return 0
chat_id = update.message["chat"]["id"]
if update.message["chat"]["type"] == "private":
name = update.message["chat"]["first_name"]
else:
name = update.message["from_user"]["first_name"]

with open("msg/start.md") as start_file:
try:
start_text = start_file.read()
start_text = start_text.replace("{{name}}", name)
chatbot.send_message(
chat_id=chat_id,
text=start_text,
parse_mode=telegram.ParseMode.MARKDOWN,
)
except Exception as error:
self.logger.error(error)
try:
chat_ids = os.environ.get("CHAT_ID").replace(" ", "")
chat_ids = chat_ids.split(",")
chat_ids = [int(i) for i in chat_ids]
if chat_id not in chat_ids:
with open("msg/error.md") as error:
error = error.read()
chatbot.send_message(
chat_id=chat_id,
text=error,
parse_mode=telegram.ParseMode.MARKDOWN,
)
except Exception as error:
self.logger.error(error)
return 0

def send_daily(self, chatbot, job):
"""
Info command to know more about the developers.
@bot = information about the bot
Sends text on `daily.md` daily to groups on CHAT_ID
@BOT = information about the BOT
@update = the user info.
"""
chat_id = os.environ.get("CHAT_ID")
self.logger.info(f"Sending daily to {chat_id}")
with open("daily.md") \
as daily_file:
daily_text = daily_file.read()
chatbot.send_message(
chat_id=chat_id,
text=daily_text,
parse_mode=telegram.ParseMode.MARKDOWN,
)
return 0
chat_ids = os.environ.get("CHAT_ID").replace(" ", "")
chat_ids = chat_ids.split(",")
for chat_id in chat_ids:
self.logger.info(f"Sending daily to {chat_id}")
with open("msg/daily.md") as daily_file:
daily_text = daily_file.read()
chatbot.send_message(
chat_id=chat_id,
text=daily_text,
parse_mode=telegram.ParseMode.MARKDOWN,
)
return 0

def send_example(self, chatbot, update):
"""
Sends example to caller
@chatbot = information about the bot
@chatbot = information about the BOT
@update = the user info.
"""
self.send_type_action(chatbot, update)
self.logger.info("Example command received.")
with open("example.md") \
as example_file:
with open("msg/example.md") as example_file:
example_text = example_file.read()
print(example_text)
chatbot.send_message(
Expand All @@ -121,12 +143,12 @@ def error(self, chatbot, update, error):

def run(self):
# Start the Bot
self.logger.info("Polling bot.")
self.logger.info("Polling BOT.")
self.updater.start_polling()

# Run the bot until you press Ctrl-C or the process receives SIGINT,
# Run the BOT until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
# start_polling() is non-blocking and will stop the BOT gracefully.
self.updater.idle()
return 0

Expand All @@ -140,20 +162,20 @@ def run(self):
LINK = os.environ.get("LINK")
if TOKEN is not None:
if PORT is not None:
bot = DailyBot(TOKEN)
bot.updater.start_webhook(
BOT = DailyBot(TOKEN)
BOT.updater.start_webhook(
listen="0.0.0.0",
port=int(PORT),
url_path=TOKEN)
if LINK:
bot.updater.bot.set_webhook(LINK)
BOT.updater.bot.set_webhook(LINK)
else:
bot.updater.bot.set_webhook(f"https://{NAME}.herokuapp.com/{TOKEN}")
bot.updater.idle()
BOT.updater.bot.set_webhook(f"https://{NAME}.herokuapp.com/{TOKEN}")
BOT.updater.idle()
else:
# Run on local system once detected that it's not on Heroku nor ngrok
bot = DailyBot(TOKEN)
bot.run()
BOT = DailyBot(TOKEN)
BOT.run()
else:
HOUR = int(os.environ.get("HOUR"))
MINUTE = int(os.environ.get("MINUTE"))
Expand Down
File renamed without changes.
1 change: 1 addition & 0 deletions msg/error.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*Aviso*: chat atual não se encontra cadastrado para receber mensagem da daily.
File renamed without changes.
1 change: 1 addition & 0 deletions msg/start.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Olá, {{name}}, estou aqui para te lembrar de mandar sua daily todo dia! TODO. SANTO. DIA.
1 change: 0 additions & 1 deletion start.md

This file was deleted.

6 changes: 6 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[pycodestyle]
count = True
;ignore = E226,E302,E41
max-line-length = 100
statistics = True
exclude = venv/

0 comments on commit bfb5395

Please sign in to comment.