some strange changes for async

This commit is contained in:
dan63047 2020-04-10 19:06:15 +03:00
parent 3717461445
commit cadf924018
2 changed files with 25 additions and 25 deletions

View File

@ -5,6 +5,7 @@ import logging
import pyowm import pyowm
import random import random
import json import json
import asyncio
import wikipediaapi as wiki import wikipediaapi as wiki
from config import vk, owm, vk_mda from config import vk, owm, vk_mda
from vk_api.longpoll import VkLongPoll, VkEventType from vk_api.longpoll import VkLongPoll, VkEventType
@ -110,12 +111,15 @@ class VkBot:
return answer return answer
def exchange_rates(self): def exchange_rates(self):
rates_USD = json.loads(requests.get("https://www.nbrb.by/api/exrates/rates/145?periodicity=0").text) try:
rates_EUR = json.loads(requests.get("https://www.nbrb.by/api/exrates/rates/292?periodicity=0").text) rates_USD = json.loads(requests.get("https://www.nbrb.by/api/exrates/rates/145?periodicity=0", timeout=10).text)
rates_RUB = json.loads(requests.get("https://www.nbrb.by/api/exrates/rates/298?periodicity=0").text) rates_EUR = json.loads(requests.get("https://www.nbrb.by/api/exrates/rates/292?periodicity=0", timeout=10).text)
return "Текущий курс валют по данным НБ РБ:<br>"+rates_USD['Cur_Name']+": "+str(rates_USD['Cur_Scale'])+" "+rates_USD['Cur_Abbreviation']+" = "+str(rates_USD['Cur_OfficialRate'])+" BYN<br>"+rates_EUR['Cur_Name']+": "+str(rates_EUR['Cur_Scale'])+" "+rates_EUR['Cur_Abbreviation']+" = "+str(rates_EUR['Cur_OfficialRate'])+" BYN<br>"+"Российский рубль"+": "+str(rates_RUB['Cur_Scale'])+" "+rates_RUB['Cur_Abbreviation']+" = "+str(rates_RUB['Cur_OfficialRate'])+" BYN" rates_RUB = json.loads(requests.get("https://www.nbrb.by/api/exrates/rates/298?periodicity=0", timeout=10).text)
return "Текущий курс валют по данным НБ РБ:<br>"+rates_USD['Cur_Name']+": "+str(rates_USD['Cur_Scale'])+" "+rates_USD['Cur_Abbreviation']+" = "+str(rates_USD['Cur_OfficialRate'])+" BYN<br>"+rates_EUR['Cur_Name']+": "+str(rates_EUR['Cur_Scale'])+" "+rates_EUR['Cur_Abbreviation']+" = "+str(rates_EUR['Cur_OfficialRate'])+" BYN<br>"+"Российский рубль"+": "+str(rates_RUB['Cur_Scale'])+" "+rates_RUB['Cur_Abbreviation']+" = "+str(rates_RUB['Cur_OfficialRate'])+" BYN"
except Exception as mda:
return "Невозможно получить данные из НБ РБД: "+str(mda)
def new_message(self, message): async def new_message(self, message):
respond = {'attachment': None, 'text': None} respond = {'attachment': None, 'text': None}
message = message.split(' ', 1) message = message.split(' ', 1)
if message[0] == self._COMMANDS[0]: if message[0] == self._COMMANDS[0]:

View File

@ -2,6 +2,7 @@ import vk_api
import time import time
import logging import logging
import requests import requests
import asyncio
from config import vk, group_id from config import vk, group_id
from dan63047bot import VkBot from dan63047bot import VkBot
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
@ -12,12 +13,6 @@ handler = logging.FileHandler('bot.log', 'w', 'utf-8')
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
root_logger.addHandler(handler) root_logger.addHandler(handler)
def write_msg(peer_id, message, attachment=None):
vk.method('messages.send', {'peer_id': peer_id,
'message': message,
'random_id': time.time(),
'attachment': attachment})
longpoll = VkBotLongPoll(vk, group_id) longpoll = VkBotLongPoll(vk, group_id)
def listening(): def listening():
@ -29,21 +24,22 @@ def listening():
logging.warning("Беды с ВК: "+str(mda)) logging.warning("Беды с ВК: "+str(mda))
continue continue
async def main():
for event in listening():
try:
if event.type == VkBotEventType.MESSAGE_NEW:
logging.info(f'Новое сообщение в чате id{event.message.peer_id}: {event.message.text}')
bot = VkBot(event.message.peer_id, event.message.from_id)
result = await bot.new_message(event.message.text)
message = vk.method('messages.send', {'peer_id': event.message.peer_id, 'message': result['text'], 'random_id': time.time(), 'attachment': result['attachment']})
logging.info(f'Ответ бота: {result}')
logging.info(f'Отправлено методом messages.send: {message}')
except Exception as kek:
logging.warning("Беды с ботом: "+str(kek))
continue
logging.info("Бот начал работу") logging.info("Бот начал работу")
for event in listening(): asyncio.run(main())
try:
if event.type == VkBotEventType.MESSAGE_NEW:
logging.info(f'Новое сообщение в чате id{event.message.peer_id}: {event.message.text}')
bot = VkBot(event.message.peer_id, event.message.from_id)
bot_answer = bot.new_message(event.message.text)
if bot_answer['text'] or bot_answer['attachment']:
write_msg(event.message.peer_id, bot_answer['text'], bot_answer['attachment'])
logging.info(f'Ответ бота: {bot_answer}')
except Exception as kek:
logging.warning("Беды с ботом: "+str(kek))
continue