Пример #1
0
    async def on_message(self, message: discord.Message):

        if message.content.startswith('$hello'):
            print(message.content)
            await message.channel.send(
                'Hello {0.author.name}!'.format(message), tts=True)

        elif message.content.startswith('$help') or message.content.startswith(
                '$info'):
            print(message.content)
            await message.channel.send(INFO)
            # Выводи в чат информацию по работе с ботом

        elif message.content.startswith(
                'шо там в мире?') or message.content.startswith('$world'):
            print(message.content)
            api = CovId19Data(force=False)
            res = api.get_stats()
            await message.channel.send(get_text(res, 'во всем мире'))
            # Выводи в чат статистику по миру

        elif message.content.startswith(
                'Как там родина моя?') or message.content.startswith(
                    '$russia'):
            print(message.content)
            api = CovId19Data(force=False)
            res = api.filter_by_country('Russia')
            await message.channel.send(get_text(res, 'в России'))
            # Выводи в чат статистику по России

        elif message.content.startswith('$country'):
            print(message.content)
            api = CovId19Data(force=False)
            country = message.content[9:].lower()
            available = api.show_available_countries()
            flag = True
            for collection in table:
                if country in map(lambda i: i.lower(), collection):
                    for item in collection:
                        if item in available:
                            res = api.filter_by_country(item)
                            flag = False
                            await message.channel.send(
                                get_text(res,
                                         'в стране - {}'.format(collection[0]))
                            )
                            break
                    break
            if flag:
                await message.channel.send(
                    'К сожалению такой страны нет в базе данных')
Пример #2
0
def parse(_, msg):
    previos = 352950  #351674
    app.send_message(chat_id, 'Bot started! :' + str(datetime.datetime.now()))
    while (True):
        api = CovId19Data(force=False)
        timebnow = datetime.datetime.now()
        if timebnow.minute == 40:  # and timebnow.second == 0:# and timebnow.hour == hou_r: #True:
            location = res = api.filter_by_country('belarus')
            recovered = location['recovered']
            deaths = location['deaths']
            confirmed = location['confirmed']
            #previos = previos1
            message = 'Данные на сегодня: ' + str(
                confirmed) + ' подтвержденных случаев, ' + str(
                    deaths) + ' смерть(ей), ' + str(
                        recovered) + ' случаев выздоровления.'
            #if previos != 0 and not (previos == confirmed):
            message += '\n' + 'За сутки выявлено ' + str(
                confirmed - previos) + ' новых случаев.'
            hour = datetime.datetime.now().hour
            if (hour == 23):
                previos = confirmed
            app.send_message(chat_id, message)
            sleep(50)
        else:
            sleep(50)
Пример #3
0
async def covid_stats(message: types.Message):
    logging.info(
        f"{message.from_user.first_name, message.from_user.username, message.from_user.id} ввел {message.text}"
    )
    from covid.api import CovId19Data
    api = CovId19Data(force=False)
    res = api.get_history_by_country("russia")

    russia = res['russia']
    history = russia['history']

    current_day = list(history.keys())[-1]
    before_day = list(history.keys())[-2]

    current_info = history[current_day]
    before_info = history[before_day]

    confirmed = current_info['confirmed']
    confirmed_delta = current_info['confirmed'] - before_info['confirmed']

    recovered = current_info['recovered']
    recovered_delta = current_info['recovered'] - before_info['recovered']

    deaths = current_info['deaths']
    deaths_delta = current_info['deaths'] - before_info['deaths']

    date = current_day.split()[0]

    await message.answer(
        text=f"Статистика по коронавирусу в России:\n"
        f"<i>Информация актуальна на {date}</i>\n"
        f"Заболеваний: <b>{confirmed}</b> ( <b>+{confirmed_delta}</b> за сутки )\n"
        f"Выздоровлений: <b>{recovered}</b> ( <b>+{recovered_delta}</b> за сутки )\n"
        f"Смертей: <b>{deaths}</b> ( <b>+{deaths_delta}</b> за сутки )")
Пример #4
0
class HistoryHandler(tornado.web.RequestHandler):

    api = CovId19Data(force=False)

    def get(self):
        logging.info("recieved request for get stat")
        data = self.api.get_history_by_country("india")
        logging.info(data)
        self.write(json.dumps(data))
Пример #5
0
def covid_info(update, context):
    c_stat()
    context.bot.send_photo(update.message.chat.id, open('c_stat.png', 'rb'))
    api = CovId19Data(force=False)
    res = api.filter_by_country("russia")
    update.message.reply_text(
        f'На текущий момент: {res.get("confirmed")} подтвержденных случаев,\n '
        f'умерло - {res.get("deaths")},\n'
        f'выздоровело - {res.get("recovered")}.')
Пример #6
0
def sender(context):
    context.bot.send_message(
        -1001171884119,
        f'Уже {datetime.date.today()}, а мы до сих пор еще ничего не сделали!')
    c_stat()
    context.bot.send_photo(-1001171884119, open('c_stat.png', 'rb'))
    api = CovId19Data(force=False)
    res = api.filter_by_country("russia")
    context.bot.send_message(
        -1001171884119,
        f'На текущий момент: {res.get("confirmed")} подтвержденных случаев,\n '
        f'{res.get("deaths")} умерло,\n'
        f'{res.get("recovered")} выздоровело.')
Пример #7
0
class CountryListHandler(tornado.web.RequestHandler):

    api = CovId19Data(force=False)

    def set_default_headers(self):
        print("setting headers!!!")
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        self.set_header('Access-Control-Allow-Methods', "GET, OPTIONS")
        self.set_header("Access-Control-Allow-Headers", "access-control-allow-origin,authorization,content-type") 

    def get(self):
        data = self.api.show_available_countries()
        self.set_default_headers()
        self.write(json.dumps(data))
        
    def options(self):
        # no body
        self.set_status(204)
        self.finish()
Пример #8
0
def c_stat():
    # для статистики
    api = CovId19Data(force=False)
    x = []
    confirmed = []
    deaths = []

    res2 = api.get_history_by_country("russia")

    for dates in res2.get('russia').get('history'):
        date = DT.datetime.strptime(dates, '%Y-%m-%d %H:%M:%S').date()
        x.append(date.strftime('%m/%d'))

    for cases in res2.get('russia').get('history').keys():
        confirmed.append(
            res2.get('russia').get('history').get(cases)['confirmed'])

    fig, ax = plt.subplots()
    ax.xaxis.set_major_locator(ticker.MultipleLocator(8))
    #  Устанавливаем интервал вспомогательных делений:
    ax.xaxis.set_minor_locator(ticker.MultipleLocator(2))

    ax.plot(x, confirmed, color='r', linewidth=3)

    #  Добавляем линии основной сетки:
    ax.grid(which='major', color='k')

    #  Включаем видимость вспомогательных делений:
    ax.minorticks_on()
    #  Теперь можем отдельно задавать внешний вид
    #  вспомогательной сетки:
    ax.grid(which='minor', color='gray', linestyle=':')

    plt.xticks(rotation=60)
    ax.set_title('Подтвержденные случаи COVID-19 в России', fontsize=16)
    ax.set_xlabel('Период', fontsize=14)
    ax.set_ylabel('Количество людей', fontsize=14)

    fig.tight_layout()
    # plt.show()
    fig.savefig('c_stat')
Пример #9
0
class HistoryHandler(tornado.web.RequestHandler):

    api = CovId19Data(force=False)

    def set_default_headers(self):
        print("setting headers!!!")
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        self.set_header('Access-Control-Allow-Methods', "GET, OPTIONS")
        self.set_header("Access-Control-Allow-Headers", "access-control-allow-origin,authorization,content-type") 

    def get(self):
        country = self.get_argument('country', 'india');
        logging.info("recieved request for get stat, country-{}".format(country))
        data = self.api.get_history_by_country(country)
        self.set_default_headers()
        self.write(json.dumps(data))
         
    def options(self):
        # no body
        self.set_status(204)
        self.finish()
Пример #10
0
from covid.api import CovId19Data

api = CovId19Data(force=True)
res = api.get_stats()

res = api.get_all_records_by_country()
country = []
confirm = []
death = []
recover = []
for i in res:
    #print(res[i]['label'],"          ",res[i]['confirmed'])
    country.append(res[i]['label'])
    confirm.append(res[i]['confirmed'])
    death.append(res[i]['deaths'])
    recover.append(res[i]['recovered'])
    print(res[i])

print(country)
print(confirm)
print(death)
print(recover)
Пример #11
0
from covid.api import CovId19Data
import requests
import csv
import json

api = CovId19Data(force=False)

res = api.get_stats()


# GLOBAL STATS
def get_stats():
    confirmed = str("{:,}".format(res['confirmed']))
    recovered = str("{:,}".format(res['recovered']))
    deaths = str("{:,}".format(res['deaths']))

    return ("*Latest COVID-19 Stats: Global* \n"
            ":black_small_square: *Confirmed Cases:* " + confirmed + "\n" +
            ":black_small_square: *Recovered Cases:* " + recovered + "\n" +
            ":black_small_square: *Deaths:* " + deaths)


# STATS BY COUNTRY
def stats_country(country):
    res = api.filter_by_country(country)
    confirmed = str("{:,}".format(res['confirmed']))
    recovered = str("{:,}".format(res['recovered']))
    deaths = str("{:,}".format(res['deaths']))

    country = res['label']
Пример #12
0
 def __init__(self):
     self.api = CovId19Data(force=False)
     self._available = self.api.show_available_countries()