-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
150 lines (110 loc) · 4.89 KB
/
bot.py
File metadata and controls
150 lines (110 loc) · 4.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import sys, traceback
from config import URL_COUNTRIES, URL_ALL
import cloudinary
import os
import logging
import requests
import telegram
from telegram import InlineQueryResultArticle, InputTextMessageContent, InlineQueryResultPhoto, InlineKeyboardButton, \
InlineKeyboardMarkup
from uuid import uuid4
from mapa import crear_imagen
from datetime import datetime, timedelta
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
def consulta(pais='Colombia'):
return requests.get(URL_COUNTRIES + pais).json()
def total():
resp = requests.get(URL_ALL)
if resp.status_code != 200:
return resp.status_code, '', ''
cases = resp.json()['cases']
deaths = resp.json()['deaths']
recovered = resp.json()['recovered']
return 'A nivel mundial, hasta el momento, se tienen las siguientes cifras:' \
'\nCasos: {}.\nMuertos: {}.\nRecuperados: {}.'.format(cases, deaths, recovered)
def casos():
return 'El total de casos de Coronavirus en Colombia es {}.'.format(consulta()['cases'])
def casos_hoy():
return 'El total de casos de Coronavirus confirmados hoy en Colombia es {}.'.format(consulta()['todayCases'])
def recuperados():
return 'El total de pacientes recuperados del Coronavirus en Colombia es {}.'.format(consulta()['recovered'])
def muertos():
return 'El total de muertos por Coronavirus en Colombia es {}.'.format(consulta()['deaths'])
def start(update, context):
update.message.reply_text(
'Bienvenido a este bot que le brinda información sobre los casos de enfermos, '
'muertos y recuperados del Coronavirus en Colombia. :-)')
def mapa(update, context):
chat_id = update.message.chat.id
FILE = "mapa.jpg"
# TODO verificar si el archivo existe
fecha = os.path.getmtime(FILE)
diff = datetime.now() - datetime.fromtimestamp(fecha)
delta = timedelta(hours=2)
if diff > delta:
crear_imagen()
context.bot.send_photo(chat_id, open(FILE, 'rb'))
def muertes(update, context):
chat_id = update.message.chat.id
FILE = "muertes.jpg"
# TODO verificar si el archivo existe
fecha = os.path.getmtime(FILE)
diff = datetime.now() - datetime.fromtimestamp(fecha)
delta = timedelta(hours=2)
if diff > delta:
crear_imagen(criteria='deaths', filename=FILE)
context.bot.send_photo(chat_id, open(FILE, 'rb'))
def test(update, context):
keyboard = [[InlineKeyboardButton("Option 1", callback_data='1'),
InlineKeyboardButton("Option 2", callback_data='2')],
[InlineKeyboardButton("Option 3", callback_data='3')]]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('Please choose:', reply_markup=reply_markup)
def button(update, context):
query = update.callback_query
query.edit_message_text(text="Selected option: {}".format(query.data))
def url_from_name(filename):
return cloudinary.api.resource(filename)['url']
def inline_query(update, context):
results = [
InlineQueryResultArticle(
id=uuid4(),
title="Mundo",
thumb_url="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Erioll_world_2.svg/1024px-Erioll_world_2.svg.png",
thumb_width="32",
thumb_height="32",
input_message_content=InputTextMessageContent(total())),
InlineQueryResultArticle(
id=uuid4(),
title="Casos",
input_message_content=InputTextMessageContent(casos())),
InlineQueryResultArticle(
id=uuid4(),
title="Muertos",
input_message_content=InputTextMessageContent(muertos())),
InlineQueryResultArticle(
id=uuid4(),
title="Recuperados",
input_message_content=InputTextMessageContent(recuperados())),
InlineQueryResultPhoto(
id=uuid4(),
title="Mapa de Casos",
caption="Mapa de Casos",
description="Mapa de Casos",
photo_url=url_from_name('mapa.jpg'),
thumb_url='https://res.cloudinary.com/dlyc7rdxt/image/upload/ar_1:1,b_rgb:262c35,bo_5px_solid_rgb:ff0000,c_fill,g_auto,r_max,t_media_lib_thumb,w_100/v1584293147/coronavirus_w28z7e.jpg'),
InlineQueryResultPhoto(
id=uuid4(),
title="Mapa de Muertes",
caption="Mapa de Muertes",
description="Mapa de Muertes",
photo_url=url_from_name('muertes.jpg'),
thumb_url='https://res.cloudinary.com/dlyc7rdxt/image/upload/ar_1:1,b_rgb:262c35,bo_5px_solid_rgb:ff0000,c_fill,g_auto,r_max,t_media_lib_thumb,w_100/v1584293147/coronavirus_w28z7e.jpg'),
]
update.inline_query.answer(results)
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)