async def handle_message_received(message): try: await dp.throttle('start', rate=float(0.5)) except Throttled: await message.reply('Воу! Не так быстро. (Защита от флуда)') else: await bot.send_chat_action(int(message.from_user.id), "typing") data_wait = await message.reply('Думаю...') input_messages = str(message.text) input_tensor = tokenizer.encode_input(input_messages, message.from_user.id) await bot.send_chat_action(int(message.from_user.id), "typing") output_tensor = predictor.decode_sequence(input_tensor, temperature) output_message, token_count = tokenizer.decode_output( input_messages, output_tensor) if config.use_delay: await bot.send_chat_action(int(message.from_user.id), "typing") await asyncio.sleep(random.uniform(0.1, 0.2) * token_count) if output_message: await bot.edit_message_text(text=str(output_message[:2000]), chat_id=int(message.from_user.id), message_id=int(data_wait.message_id)) log( str('ID {} получил ответ - "{}"').format( str(message.from_user.id), str(output_message[:2000])))
def download_yadisk_link(sharing_link, filename=None): direct_link = _get_real_direct_link(sharing_link) if direct_link: # Try to recover the filename from the link filename = filename or _extract_filename(direct_link) download = requests.get(direct_link) with open(filename, "wb") as out_file: out_file.write(download.content) log('Успешно скачал "{}" в "{}"'.format(sharing_link, filename)) else: log('Не удалось скачать "{}"'.format(sharing_link))
async def on_guild_emojis_update(self, guild, before, after): await self.wait_until_ready() log(f"На сервере {guild.name} изменилась коллекция emoji.") if len(before) != len(after): self.load_custom_emoji_collection()
async def on_guild_remove(self, guild): await self.wait_until_ready() log(f"Вышел с сервера {guild.name}.") self.load_custom_emoji_collection()
async def on_guild_join(self, guild): await self.wait_until_ready() log(f"Зашел на сервер {guild.name}.") self.load_custom_emoji_collection()
async def on_ready(self): log(f"Подключение к Discord успешно под пользователем @{self.user}.") self.load_custom_emoji_collection() game = discord.Game(config.discord_game_name) await self.change_presence(activity=game)
def load_custom_emoji_collection(self): self.custom_emoji_collection.clear() guilds = list(self.guilds) for guild in guilds: self.custom_emoji_collection.extend(guild.emojis) log("Коллекция кастомных emoji обновлена.")
from scipy.special import softmax from core.tf_transformer import transformer import config from utils.tprint import log from tqdm import tqdm # Параментры Transformer взяты из оригинальной публикации: # https://arxiv.org/abs/1706.03762 (стр. 9 - base) NUM_LAYERS = 6 D_MODEL = 512 NUM_HEADS = 8 UNITS = 2048 DROPOUT = 0.1 log(f'Загружаю {config.weights_file}...') model = transformer( vocab_size=config.vocab_size, num_layers=NUM_LAYERS, units=UNITS, d_model=D_MODEL, num_heads=NUM_HEADS, dropout=DROPOUT) model.load_weights(config.weights_file) model.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy']) log(f'{config.weights_file} загружен.')
from core.tf_transformer import transformer import config from core.yadisk import download_yadisk_link from utils.tprint import log from tqdm import tqdm # Параментры Transformer взяты из оригинальной публикации: # https://arxiv.org/abs/1706.03762 (стр. 9 - base) NUM_LAYERS = 6 D_MODEL = 512 NUM_HEADS = 8 UNITS = 2048 DROPOUT = 0.1 log(f"Загружаю {config.weights_file}...") model = transformer( vocab_size=config.vocab_size, num_layers=NUM_LAYERS, units=UNITS, d_model=D_MODEL, num_heads=NUM_HEADS, dropout=DROPOUT, ) try: model.load_weights(config.weights_file) except OSError: log(f"Похоже весов нет! Попробую скачать с Яндекс.Диска, подождите 2 минуты...") with open("weights/weights.txt") as f: url = f.readline().strip()
# Основной модуль DolboNet # by Wokashi RG # https://github.com/wokashi-rg import discord from core.checking_client import CheckingClient import config from utils.tprint import log import asyncio log('Проверяю Discord токен...') checking_client = CheckingClient() login_successful = False try: checking_client.run(config.token) login_successful = True except discord.errors.LoginFailure: log('НЕВЕРНЫЙ DISCORD ТОКЕН! Необходимо отредактировать файл config.py!') if login_successful: log('Discord токен проверен.') asyncio.set_event_loop(asyncio.new_event_loop()) from core.main_client import MainClient main_client = MainClient() main_client.run(config.token)