Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinsMessias committed Nov 29, 2022
1 parent b8284b0 commit 1ac62e2
Show file tree
Hide file tree
Showing 9 changed files with 67 additions and 52 deletions.
6 changes: 6 additions & 0 deletions .env_example
Original file line number Diff line number Diff line change
@@ -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
18 changes: 0 additions & 18 deletions app.py

This file was deleted.

22 changes: 13 additions & 9 deletions bot.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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))
Expand Down
Empty file added src/__init__.py
Empty file.
13 changes: 10 additions & 3 deletions src/desciclopedia/desciclopedia.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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:
Expand Down
5 changes: 0 additions & 5 deletions src/extra.py

This file was deleted.

16 changes: 13 additions & 3 deletions src/shodan/shodan.py
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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:
Expand Down
27 changes: 17 additions & 10 deletions src/twitter/trends.py
Original file line number Diff line number Diff line change
@@ -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']
Expand All @@ -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)
Expand Down
12 changes: 8 additions & 4 deletions src/wikipedia/wikipedia.py
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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:
Expand Down

0 comments on commit 1ac62e2

Please sign in to comment.