diff --git a/.env_example b/.env_example new file mode 100644 index 0000000..486ded6 --- /dev/null +++ b/.env_example @@ -0,0 +1,6 @@ +FROM_EMAIL=mail@example.com +FROM_PWD=password +TELEGRAM_TOKEN=telegramtoken +TWITTER_TOKEN=AAAAAAAAAAAAAAAAAAAAA +SHODAN_API_KEY=AAAAAAAAAAAAAAAAAAAAA +ADMIN_CHAT_ID=000000000 diff --git a/app.py b/app.py deleted file mode 100644 index 21632d7..0000000 --- a/app.py +++ /dev/null @@ -1,18 +0,0 @@ -from flask import Flask -from flask.json import jsonify -from src.newsletter.news_letter import newsletter -from datetime import date - - -app = Flask(__name__) -app.config['SECRET_KEY'] = 'you-will-never-guess' - - -@app.route('/', methods=['GET']) -def index(): - newsletters = newsletter() - return jsonify({'data': str(date.today()), 'newsletter': newsletters}) - - -if __name__ == "__main__": - app.run(host="0.0.0.0", debug=True) diff --git a/bot.py b/bot.py index c4ab877..f5767d0 100644 --- a/bot.py +++ b/bot.py @@ -1,14 +1,18 @@ +""" +Main script +""" import logging -from time import sleep +import os +import telegram from telegram.ext import CommandHandler, Filters, MessageHandler, Updater + +# Import all functions here from src.desciclopedia.desciclopedia import desciclopedia from src.mega.mega import mega -from src.newsletter.newsletter import newsletter from src.shodan.shodan import shodan from src.twitter.trends import trends from src.wikipedia.wikipedia import wikipedia -from src.extra import bot, telegram, credentials # Enable logging @@ -47,6 +51,7 @@ def define_command(update, context): def start(update, context): """Send a message when the command /start is issued.""" + bot = telegram.Bot(token=os.environ.get('TELEGRAM_TOKEN')) bot.sendChatAction( chat_id=update.effective_chat.id, action=telegram.ChatAction.TYPING) @@ -55,7 +60,7 @@ def start(update, context): text='O pai tá ON, qual é a boa? ') -def help(update, context): +def other_help(update, context): """Send a message when the command /help is issued.""" context.bot.send_message(chat_id=update.effective_chat.id, text=''' Comandos @@ -64,7 +69,6 @@ def help(update, context): ➤ /shodan - Shodan search ➤ /wikipedia - Wikipedia search ➤ /desciclopedia - Desciclopedia search - ➤ /newsletter - Notícias do mundo tech ➤ /trends - Twitter Trendings ➤ /mega - Números para você jogar na mega. @@ -79,23 +83,23 @@ def error(update, context): """Log Errors caused by Updates.""" logger.warning('Update "%s" caused error "%s"', update, context.error) context.bot.send_message( - chat_id=credentials.ADMIN_CHAT_ID, + chat_id=os.environ.get('ADMIN_CHAT_ID'), text=f'Update {update} caused error {context.error}') def main(): """Start the bot.""" - updater = Updater(credentials.TELEGRAM_TOKEN, use_context=True) + updater = Updater(os.environ.get('TELEGRAM_TOKEN'), use_context=True) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.add_handler(CommandHandler("start", start)) - dp.add_handler(CommandHandler("help", help)) + dp.add_handler(CommandHandler("help", other_help)) dp.add_handler(CommandHandler("trends", trends)) dp.add_handler(CommandHandler("mega", mega)) - dp.add_handler(CommandHandler("newsletter", newsletter)) + # dp.add_handler(CommandHandler("newsletter", newsletter)) # on noncommand i.e message - echo the message on Telegram dp.add_handler(MessageHandler(Filters.text, define_command)) diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/desciclopedia/desciclopedia.py b/src/desciclopedia/desciclopedia.py index aa7b29d..05c6bab 100644 --- a/src/desciclopedia/desciclopedia.py +++ b/src/desciclopedia/desciclopedia.py @@ -1,8 +1,14 @@ -from src.extra import bot, telegram, credentials, requests +""" +Search for a term in the 'desciclopedia' wiki and return the first paragraph. +""" +import os +import requests +import telegram def desciclopedia(update, context): """Desciclopedia search""" + bot = telegram.Bot(token=os.environ.get('TELEGRAM_TOKEN')) bot.sendChatAction(chat_id=update.effective_chat.id, action=telegram.ChatAction.TYPING) if update.message is None: @@ -11,10 +17,11 @@ def desciclopedia(update, context): user_input = update.message.text user_input = " ".join(filter(lambda x: x[0] != '/', user_input.split())) - url = f'http://desciclopedia.org/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles={user_input}' + url = 'http://desciclopedia.org/api.php?format=json&action=' \ + 'query&prop=extracts&exintro&explaintext&redirects=1&titles=' + user_input try: - response = requests.get(url) + response = requests.get(url, timeout=5) pages = response.json()['query']['pages'] for page_num in pages: diff --git a/src/extra.py b/src/extra.py deleted file mode 100644 index dbd2735..0000000 --- a/src/extra.py +++ /dev/null @@ -1,5 +0,0 @@ -import credentials -import telegram -import requests - -bot = telegram.Bot(token=credentials.TELEGRAM_TOKEN) diff --git a/src/shodan/shodan.py b/src/shodan/shodan.py index f3ef924..2eafe50 100644 --- a/src/shodan/shodan.py +++ b/src/shodan/shodan.py @@ -1,8 +1,18 @@ +""" +Search in shodan for a term and return the firsts results. +""" import random -from src.extra import bot, telegram, credentials, requests +import os +import requests +import telegram + + +BASE_URL = 'https://api.shodan.io/shodan/host/' def shodan(update, context): + """Shodan search""" + bot = telegram.Bot(token=os.environ.get('TELEGRAM_TOKEN')) bot.sendChatAction( chat_id=update.effective_chat.id, action=telegram.ChatAction.TYPING) @@ -23,14 +33,14 @@ def shodan(update, context): update.message.reply_text( f'🔍 Procurando computadores conectados a internet pela descrição: {user_input}...') - url = f'https://api.shodan.io/shodan/host/search?key={credentials.SHODAN_API_KEY}&query={user_input}' + url = f'{BASE_URL}search?key={os.environ.get("SHODAN_API_KEY")}&query={user_input}' bot.sendChatAction( chat_id=update.effective_chat.id, action=telegram.ChatAction.TYPING) try: - result = requests.get(url).json() + result = requests.get(url, timeout=5).json() results_count = 0 if result['total'] == 0 or not result: diff --git a/src/twitter/trends.py b/src/twitter/trends.py index 1a779e9..96f1fd1 100644 --- a/src/twitter/trends.py +++ b/src/twitter/trends.py @@ -1,30 +1,36 @@ -from src.extra import bot, telegram, credentials, requests -from time import sleep +""" +Get Twitter trending topics from Brazil (São Paulo) and list the 10 most mentioned. +""" +import os +import requests +import telegram + + +BASE_URL = 'https://api.twitter.com/1.1/' def trends(update, context): """Get Twitter trending topics""" - + bot = telegram.Bot(token=os.environ.get('TELEGRAM_TOKEN')) bot.sendChatAction( chat_id=update.effective_chat.id, action=telegram.ChatAction.TYPING) try: - hed = {'Authorization': 'Bearer ' + credentials.TWITTER_TOKEN} - - url = 'https://api.twitter.com/1.1/trends/place.json?id=455827' - response = requests.get(url, headers=hed) + hed = {'Authorization': 'Bearer ' + os.environ.get('TWITTER_TOKEN')} + url = f'{BASE_URL}/trends/place.json?id=455827' + response = requests.get(url, headers=hed, timeout=5) data = [] - for trend in response.json()[0]['trends']: - clean_trend = {} if trend['promoted_content'] is None: volume = trend['tweet_volume'] + if not volume or volume == "": continue + clean_trend['name'] = trend['name'] clean_trend['volume'] = int(volume) clean_trend['url'] = trend['url'] @@ -35,7 +41,8 @@ def trends(update, context): message = "🐥 Top 10 tendências no Brasil\n" for trend in data[:10]: - message += f'\n {data.index(trend) + 1} - {trend["name"]} \nMensões: {trend["volume"]}\n' + message += f'\n {data.index(trend) + 1} '\ + ' - {trend["name"]} \nMensões: {trend["volume"]}\n' context.bot.send_message( chat_id=update.effective_chat.id, text=message) diff --git a/src/wikipedia/wikipedia.py b/src/wikipedia/wikipedia.py index 9abd7f5..f1bf5b7 100644 --- a/src/wikipedia/wikipedia.py +++ b/src/wikipedia/wikipedia.py @@ -1,9 +1,13 @@ -from src.extra import bot, telegram, credentials, requests +import os +import requests +import telegram + +BASE_URL = 'https://pt.wikipedia.org/w/api.php' def wikipedia(update, context): """Wikipedia search""" - + bot = telegram.Bot(token=os.environ.get('TELEGRAM_TOKEN')) bot.sendChatAction( chat_id=update.effective_chat.id, action=telegram.ChatAction.TYPING) @@ -14,10 +18,10 @@ def wikipedia(update, context): user_input = update.message.text user_input = " ".join(filter(lambda x: x[0] != '/', user_input.split())) - url = f'https://pt.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles={user_input}' + url = f'{BASE_URL}?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles={user_input}' try: - response = requests.get(url) + response = requests.get(url, timeout=5) pages = response.json()['query']['pages'] for page_num in pages: