Error dissnake pyanywhere
Написал бота на disnake и столкнулся с проблемой хостинга:
Traceback (most recent call last):
File "/home/popa228337123/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 1025, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs)
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 1064, in create_connection
raise exceptions[0]
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 1049, in create_connection
sock = await self._connect_sock(
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 960, in _connect_sock
await self.sock_connect(sock, address)
File "/usr/local/lib/python3.10/asyncio/selector_events.py", line 500, in sock_connect
return await fut
File "/usr/local/lib/python3.10/asyncio/selector_events.py", line 535, in _sock_connect_cb
raise OSError(err, f'Connect call failed {address}')
ConnectionRefusedError: [Errno 111] Connect call failed ('162.159.128.233', 443)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/popa228337123/dsb/bot.py", line 160, in <module>
bot.run('*токен*')
File "/home/popa228337123/.local/lib/python3.10/site-packages/disnake/client.py", line 1126, in run
return future.result()
File "/home/popa228337123/.local/lib/python3.10/site-packages/disnake/client.py", line 1105, in runner
await self.start(*args, **kwargs)
File "/home/popa228337123/.local/lib/python3.10/site-packages/disnake/client.py", line 1066, in start
await self.login(token)
File "/home/popa228337123/.local/lib/python3.10/site-packages/disnake/ext/commands/interaction_bot_base.py", line 224, in login
await super().login(token)
File "/home/popa228337123/.local/lib/python3.10/site-packages/disnake/ext/commands/common_bot_base.py", line 131, in login
await super().login(token=token) # type: ignore
File "/home/popa228337123/.local/lib/python3.10/site-packages/disnake/client.py", line 865, in login
data = await self.http.static_login(token.strip())
File "/home/popa228337123/.local/lib/python3.10/site-packages/disnake/http.py", line 462, in static_login
data: user.User = await self.request(Route("GET", "/users/@me"))
File "/home/popa228337123/.local/lib/python3.10/site-packages/disnake/http.py", line 338, in request
async with self.__session.request(method, url, **kwargs) as response:
File "/home/popa228337123/.local/lib/python3.10/site-packages/aiohttp/client.py", line 1197, in __aenter__
self._resp = await self._coro
File "/home/popa228337123/.local/lib/python3.10/site-packages/aiohttp/client.py", line 581, in _request
conn = await self._connector.connect(
File "/home/popa228337123/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 544, in connect
proto = await self._create_connection(req, traces, timeout)
File "/home/popa228337123/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 944, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
File "/home/popa228337123/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 1257, in _create_direct_connection
raise last_exc
File "/home/popa228337123/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 1226, in _create_direct_connection
transp, proto = await self._wrap_create_connection(
File "/home/popa228337123/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 1033, in _wrap_create_connection
raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host discord.com:443 ssl:default [Connect call failed ('162.159.128.233', 443)]
Сам код:
import disnake
from disnake.ext import commands, tasks
import os
import random
import json
import datetime
from loguru import logger
import asyncio
# Логи
logger.add("bot.log", rotation="80 MB")
intents = disnake.Intents.default()
intents.members = True
intents.message_content = True
intents.messages = True
intents.guilds = True
bot = commands.Bot(command_prefix='!', intents=intents)
user_data_file = 'user_data.json'
# Функция загрузки данных пользователей из файла
def load_user_data():
try:
with open(user_data_file, 'r') as f:
data = json.load(f)
# Преобразование строк обратно в datetime объекты
for user_id, user_data in data.items():
if 'last_bonus' in user_data and user_data['last_bonus'] is not None:
user_data['last_bonus'] = datetime.datetime.fromisoformat(
user_data['last_bonus']
)
logger.info("Данные пользователей успешно загружены") # Логи
return data
except FileNotFoundError:
logger.warning(
"Файл с данными пользователей не найден. Будет создан новый файл." # Лог ошибки
)
return {}
# Функция сохранения данных пользователей в файл
def save_user_data(data):
with open(user_data_file, 'w') as f:
# Преобразование datetime объектов в строки перед записью в JSON
for user_id, user_data in data.items():
if 'last_bonus' in user_data and isinstance(
user_data['last_bonus'], datetime.datetime
):
user_data['last_bonus'] = user_data['last_bonus'].isoformat()
json.dump(data, f, indent=4)
logger.info("Данные пользователей сохранены") # Логи
user_data = load_user_data()
# Функция выдачи бонуса пользователю
def give_bonus(user_id):
user_id = str(user_id)
if user_id not in user_data:
user_data[user_id] = {'balance': 0, 'last_bonus': None}
if user_data[user_id]['last_bonus'] is None or (
datetime.datetime.now() - datetime.datetime.fromisoformat(user_data[user_id]['last_bonus'].isoformat())
).total_seconds() >= 86400:
bonus_amount = random.randint(-7, 20)
user_data[user_id]['balance'] += bonus_amount
user_data[user_id]['last_bonus'] = datetime.datetime.now().isoformat()
save_user_data(user_data)
return True
return False
@bot.event
async def on_ready():
logger.info(f'Бот {bot.user} подключен к Discord!') # Логи
last_pinged_user = None
@bot.event
async def on_message(message):
global last_pinged_user
if bot.user.mentioned_in(message):
if not reset_ping.is_running():
reset_ping.start()
if message.author.id == last_pinged_user:
await message.channel.send("Да чё тебе от меня надо? /info напиши уже и не пингуй меня, бездарь")
else:
phrases = ["Чо нада?", "Чо хотел?"]
random_phrase = random.choice(phrases)
await message.channel.send(random_phrase)
last_pinged_user = message.author.id
await bot.process_commands(message)
@tasks.loop(seconds=300)
async def reset_ping():
global last_pinged_user
last_pinged_user = None
logger.info('Память о пингах сброшена')
@bot.slash_command(name='info', description='Узнать команды бота')
async def infa(interaction: disnake.ApplicationCommandInteraction):
sms = f"**Список команд:**\n\n!razmer - Узнать размер линейки\n!lin - Вырастить/уменьшить линейку\n!top - Топ линеек\n/ping - Узнать пинг бота"
await interaction.response.send_message(embed=disnake.Embed(description = sms, color = disnake.Color.orange()))
@bot.slash_command(name="sync", description="Синхронизирует Slash-команды")
@commands.is_owner()
async def sync(interaction: disnake.ApplicationCommandInteraction):
try:
await bot._sync_application_commands()
await interaction.response.send_message("✅ Slash-команды успешно синхронизированы!", ephemeral=True)
except disnake.HTTPException as e:
await interaction.response.send_message(f"❌ Ошибка при синхронизации команд: {e}", ephemeral=True)
@bot.command(name="ping", description="Показывает пинг бота")
async def ping(ctx):
await ctx.send(embed=disnake.Embed(description = f"? Понг! Задержка: {round(bot.latency * 1000)} мс", color = disnake.Color.orange()))
@bot.command(name='razmer')
async def balance(ctx):
user_id = str(ctx.author.id)
if user_id not in user_data:
user_data[user_id] = {'balance': 0, 'last_bonus': None}
save_user_data(user_data)
await ctx.send(f"{ctx.author.mention}, твоя линейка: {user_data[user_id]['balance']} см.?")
@bot.command(name='lin')
async def bonus(ctx):
user_id = str(ctx.author.id)
if give_bonus(user_id):
sms = f"{ctx.author.mention}\nТы получил бонусные см"
await ctx.send(embed=disnake.Embed(description = sms, color = disnake.Color.orange()))
else:
sms = f"{ctx.author.mention}\nКД в 24 часа ещё не прошло, жди дальше..."
await ctx.send(embed=disnake.Embed(description = sms, color = disnake.Color.orange()))
@bot.command(name='top')
async def top(ctx):
top_users = sorted(user_data.items(), key=lambda x: x[1]['balance'], reverse=True)[:10]
top_list = "? **Топ линеек:**\n\n"
for i, (user_id, data) in enumerate(top_users):
user = await bot.fetch_user(int(user_id)) # Получение объекта пользователя по ID
top_list += f"{i+1}. {user.name} - {data['balance']} см\n"
await ctx.send(embed=disnake.Embed(description = top_list, color = disnake.Color.orange()))
@bot.slash_command(name="top", description= "Узнать топ линеек")
async def topchik(ctx):
top_users = sorted(user_data.items(), key=lambda x: x[1]['balance'], reverse=True)[:10]
top_list = "? **Топ линеек:**\n\n"
for i, (user_id, data) in enumerate(top_users):
user = await bot.fetch_user(int(user_id)) # Получение объекта пользователя по ID
top_list += f"{i+1}. {user.name} - {data['balance']} см\n"
await ctx.send(embed=disnake.Embed(description = top_list, color = disnake.Color.orange()))
bot.run('*токен*')
Узнал только то, что нужно использовать прокси, но как интегрировать его в этот код я понятия не имею, помогите!