Запуск Discrod бота на Sparked Host через токен
Вчера залил discrod бота Sparked Host с данным кодом (немного вырезал код, чтобы поместилось):
import discord
from discord.ext import commands
from config_croupe import settings
import os
import json
import requests
import random
import pickle
import time as time
import datetime
bot = commands.Bot(command_prefix=settings['prefix'], intents=discord.Intents.all())
bot.remove_command('help')
max_retries = 5
attempt = 0
@bot.event
async def on_ready():
print('Bot is online')
# Specials
bot.casino_channel = 1010966992309719141
bot.dev_channel = 1010978701648871554
bot.min_transfer = 10000
# Casino
bot.imgs_link = "https://api.jsonbin.io/v3/b/62ff67f5e13e6063dc827980"
bot.bet_input = -1
bot.bet_winning = 10000
bot.black_sectors = ['2', '4', '6', '8', '10', '11', '13', '15', '17',
'20', '22', '24', '26', '28', '29', '31', '33', '35']
bot.red_sectors = ['1', '3', '5', '7', '9', '12', '14', '16', '18',
'19', '21', '23', '25', '27', '30', '32', '34', '36']
bot.words_sectors = ['red', 'black', 'odd', 'even', '00', '0', '1st12',
'2nd12', '3rd12', '1to18', '19to36', '2to1_1', '2to1_2', '2to1_3']
bot.first_2to1 = ['1', '4', '7', '10', '13', '16', '19', '22', '25', '28', '31', '34']
bot.second_2to1 = ['2', '5', '8', '11', '14', '17', '20', '23', '26', '29', '32', '35']
bot.third_2to1 = ['3', '6', '9', '12', '15', '18', '21', '24', '27', '30', '33', '36']
bot.green = int('00FF00', base=16)
bot.red = int('FF0000', base=16)
bot.black = int('000000', base=16)
def bets_payment(coefficient: int, author_id: str, points: int):
with open('casino_stats.py', 'rb') as inp:
stats = pickle.load(inp)
if coefficient == 38 and stats[author_id]['points'] < bot.bet_winning:
coefficient = 10
stats[author_id]['points'] += points * coefficient
with open('casino_stats.py', 'wb') as out:
pickle.dump(stats, out)
def bets_checker(bet_arr):
checking_arr = bot.red_sectors + bot.black_sectors + bot.words_sectors
for i in bet_arr:
if i not in checking_arr:
return True
return False
def bets_winners(bet_arr, author_id: str, result: int, points: int):
cheker = False
str_result = str(result)
if result == 37:
str_result = '00'
for i in bet_arr:
if i == str_result:
bets_payment(38, author_id, points)
cheker = True
if i.lower() == "red" and str_result in bot.red_sectors:
bets_payment(2, author_id, points)
cheker = True
if i.lower() == "black" and str_result in bot.black_sectors:
cheker = True
bets_payment(2, author_id, points)
if i.lower() == "even" and result % 2 == 0 and result != 0:
cheker = True
bets_payment(2, author_id, points)
if i.lower() == "odd" and result % 2 != 0:
cheker = True
bets_payment(2, author_id, points)
if i.lower() == "1st12" and 1 <= result <= 12:
cheker = True
bets_payment(3, author_id, points)
if i.lower() == "2nd12" and 12 <= result <= 24:
cheker = True
bets_payment(3, author_id, points)
if i.lower() == "3rd12" and 24 <= result <= 36:
cheker = True
bets_payment(3, author_id, points)
if i.lower() == "2to1_1" and str_result in bot.first_2to1:
cheker = True
bets_payment(3, author_id, points)
if i.lower() == "2to1_2" and str_result in bot.second_2to1:
cheker = True
bets_payment(3, author_id, points)
if i.lower() == "2to1_3" and str_result in bot.third_2to1:
cheker = True
bets_payment(3, author_id, points)
if i.lower() == "1to18" and 1 <= result <= 18:
cheker = True
bets_payment(2, author_id, points)
if i.lower() == "19to36" and 19 <= result <= 36:
cheker = True
bets_payment(2, author_id, points)
if cheker:
return True
@bot.command()
@commands.cooldown(1, 3.6)
async def casino(ctx, points: int, *, bet: str):
channel = discord.utils.get(ctx.guild.text_channels, id=bot.casino_channel)
author = ctx.message.author
author_id = str(author.id)
with open('casino_stats.py', 'rb') as inp:
stats = pickle.load(inp)
if channel:
if ctx.channel != channel:
await ctx.send("**❌ В этом канале мы не можем играть в рулетку! ❌**")
else:
with open('ban_list.py', 'rb') as inp:
bans = pickle.load(inp)
if author_id in bans:
if time.time() - bans[author_id]['ban_time'] >= bans[author_id]['time_from']:
bans.pop(str(author_id))
with open('ban_list.py', 'wb') as out:
pickle.dump(bans, out)
else:
await ctx.send(f"**{author.mention}, ты кто такой, сука?! Ты забанен, черт! Тебе осталось ещё "
f"{time.strftime('%H:%M:%S',time.gmtime(bans[author_id]['ban_time']+bans[author_id]['time_from']-time.time()))}!?**")
return False
if author_id not in stats:
new_user = {'name': str(author), 'victories': 0, 'defeats': 0, 'points': 5000, 'max_points': 0}
stats[author_id] = new_user
bet_arr = list(map(str, bet.split(' ')))
if len(bet_arr) < 1:
await ctx.send("**Ставить будешь на что, черт?! ?**")
return False
if len(bet_arr) > 3:
await ctx.send("**Слишком много ставок, чертила! ?**")
else:
if points * len(bet_arr)>stats[author_id]['points'] and bot.bet_input==-1 and stats[author_id]['' \
'points']>0:
await ctx.send(
f"**Многовато ставишь, черт! Давай поскромнее! Твой максимум "
f"{int(stats[author_id]['points'] / len(bet_arr))}** ?") # на {len(bet_arr)} ставки!**")
return False
if points * len(bet_arr) > bot.bet_input > 1 and stats[author_id]['points'] > 0:
await ctx.send(f"**Многовато ставишь, черт! Давай поскромнее! Твой максимум {bot.bet_input} ?**")
return False
if 0 < bot.bet_input < 1 and points * len(bet_arr) > stats[author_id][
'points'] * bot.bet_input:
await ctx.send(
f"**Многовато ставишь, черт! Давай поскромнее! Твой максимум "
f"{int(stats[author_id]['points'] * bot.bet_input)}** ?")
return False
if stats[author_id]['points'] <= 0:
stats[author_id]['points'] = 5000
await ctx.send(
f"**{author.mention}, я накинулл 5000 тебе на счёт, так как ты всё проебал!?**"
f"\n**Ставь ставку по-новой!**")
with open('casino_stats.py', 'wb') as out:
pickle.dump(stats, out)
return False
if points * len(bet_arr) <= 0:
await ctx.send(f"**{author.mention}, ты долбаёб или как? ?**")
return False
for i in range(len(bet_arr)):
bet_arr[i] = bet_arr[i].lower()
if bets_checker(bet_arr):
await ctx.send("**Пошёл нахуй, дебил: таких ставок нет! ?**")
return False
stats[author_id]['points'] -= points * len(bet_arr)
points_before = stats[author_id]['points']
with open('casino_stats.py', 'wb') as out:
pickle.dump(stats, out)
result = random.randint(0, 37)
embed = discord.Embed(color=0x36393f, title='Рулетка вращается...')
embed.set_image(url='https://c.tenor.com/92nSRpL7ukkAAAAM/casino-gamble.gif')
answer = await ctx.send(embed=embed)
time.sleep(2)
if bets_winners(bet_arr, author_id, result, points):
with open('casino_stats.py', 'rb') as inp:
stats = pickle.load(inp)
embed_res = discord.Embed(
color=0xFFC709,
title=f'Вы выиграли! Выпало:',
description=f'{author.mention}, у тебя {stats[author_id]["points"]} '
f'фишек\nТы выйграл {stats[author_id]["points"] - points_before} фишек')
response = requests.get(bot.imgs_link)
json_data = json.loads(response.text)
embed_res.set_image(url=json_data["record"][str(result)])
# await ctx.send(file=discord.File('casino_img/' + str(result) + '.png'))
await answer.edit(embed=embed_res)
with open('casino_stats.py', 'rb') as inp:
stats = pickle.load(inp)
if (bet_arr.count('red') + bet_arr.count('black') <= 1 and
bet_arr.count('even') + bet_arr.count('odd') <= 1 and
bet_arr.count('1to18') + bet_arr.count('19to36') <= 1):
stats[author_id]['victories'] += 1
if stats[author_id]['max_points'] < stats[author_id]['points'] - points_before:
stats[author_id]['max_points'] = stats[author_id]['points'] - points_before
if stats[author_id]['points'] > 1000000000:
stats[author_id]['points'] = 100000
await ctx.send(f"**{author.mention}, я порезал тебе счёт, так как ты слишком много вынес!**")
with open('casino_stats.py', 'wb') as out:
pickle.dump(stats, out)
else:
if str(result) in bot.black_sectors:
embed_color = int('000000', base=16)
elif str(result) in bot.red_sectors:
embed_color = int('FF0000', base=16)
else:
embed_color = int('00FF00', base=16)
with open('casino_stats.py', 'rb') as inp:
stats = pickle.load(inp)
stats[author_id]['defeats'] += 1
embed_res = discord.Embed(
color=embed_color,
title='Вы проиграли! Выпало:',
description=f'{author.mention}, у вас осталось {stats[author_id]["points"]} фишек')
response = requests.get(bot.imgs_link)
json_data = json.loads(response.text)
embed_res.set_image(url=json_data["record"][str(result)])
await answer.edit(embed=embed_res)
with open('casino_stats.py', 'wb') as out:
pickle.dump(stats, out)
if stats[author_id]['points'] <= 0:
stats[author_id]['points'] = 5000
await ctx.send(
f"**{author.mention}"
f", я накинулл 5000 тебе на счёт, так как ты всё проебал! ?**\n**Ставь ставку по новой!**")
with open('casino_stats.py', 'wb') as out:
pickle.dump(stats, out)
return False
# await ctx.send("Казино пока не работает! Иди нахуй лудоман!")
# Tools
@bot.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def balance(ctx):
casino_channel = discord.utils.get(ctx.guild.text_channels, id=bot.casino_channel)
if casino_channel:
if ctx.channel != casino_channel:
await ctx.send("**❌ В этом канале мы не можем просматривать ваш баланс!** ❌")
else:
author = ctx.message.author
with open('casino_stats.py', 'rb') as inp:
stats = pickle.load(inp)
if str(author.id) in stats:
await ctx.send(f'{author.mention}, у тебя {stats[str(author.id)]["points"]} фишек ?')
else:
await ctx.send(f'**В статистике вас нет, {author.mention}. А зря... ?**')
@bot.command()
@commands.cooldown(1, 1.5, commands.BucketType.user)
async def transfer(ctx, target: discord.User, value: int):
casino_channel = discord.utils.get(ctx.guild.text_channels, id=bot.casino_channel)
if casino_channel:
if ctx.channel != casino_channel:
await ctx.send("**❌ В этом канале мы не можем передавать фишки!** ❌")
else:
author = ctx.message.author
author_id = str(author.id)
with open('casino_stats.py', 'rb') as inp:
stats = pickle.load(inp)
if str(target.id) not in stats:
await ctx.send(f'**{author.mention}, такого персонажа у нас *в казино нет*** ?')
return False
if value > 10000:
await ctx.send(f'**{author.mention}, многовато фишек отдаёшь, *максимум 10000 фишек*** ?')
return False
if value < 0:
await ctx.send(f'**{author.mention}, дебил, ты реально думаешь что тебе за это заплатят?!'
f'Тебе за такое только ??**')
return False
if value > stats[author_id]["points"]:
await ctx.send(
f'**{author.mention}, у тебя фишек не хватает... На твоём счету *{stats[author_id]["points"]}'
f'* фишек ?**')
return False
if stats[author_id]["points"] < bot.min_transfer:
await ctx.send(f'**{author.mention}, при передаче фишек у тебя должно быть больше {bot.min_transfer} '
f'на счету. ?**')
else:
stats[author_id]["points"] -= value
stats[str(target.id)]["points"] += value
await ctx.send(f'**{author.mention} перевёл {target.mention} *{value} фишек ?***')
with open('casino_stats.py', 'wb') as out:
pickle.dump(stats, out)
@transfer.error
async def transfer_error(ctx, error):
await ctx.send(f"**{ctx.message.author.mention}, кому и сколько переводишь, ирод?! КОМУ И СКОЛЬКО?!?**")
@bot.command()
@commands.cooldown(1, 60*60, commands.BucketType.user)
async def zeroing(ctx):
casino_channel = discord.utils.get(ctx.guild.text_channels, id=bot.casino_channel)
if casino_channel:
if ctx.channel != casino_channel:
await ctx.send("**❌ В этом канале мы не можем обнулять статистику! ❌**")
else:
author = ctx.message.author
with open('casino_stats.py', 'rb') as inp:
stats = pickle.load(inp)
if str(author.id) in stats:
stats[str(author.id)]['points'] = 5000
stats[str(author.id)]['victories'] = 0
stats[str(author.id)]['defeats'] = 0
stats[str(author.id)]['max_points'] = 0
with open('casino_stats.py', 'wb') as out:
pickle.dump(stats, out)
await ctx.send(f'**{author.mention} обнулил свою статистику. ?**')
else:
await ctx.send(f'**В статистике нет {author.mention}. ❌**')
@bot.command()
@commands.cooldown(1, 1.5, commands.BucketType.user)
async def stats(ctx):
casino_channel = discord.utils.get(ctx.guild.text_channels, id=bot.casino_channel)
dev_channel = bot.get_channel(bot.dev_channel)
if casino_channel:
if ctx.channel != casino_channel or ctx.channel != dev_channel:
with open('casino_stats.py', 'rb') as inp:
stats = pickle.load(inp)
if not stats:
await ctx.send("**Статистика пуста ?**")
else:
result_message = ""
skip = " "
for i in stats:
if stats[i]['defeats'] == 0:
ratio = 0.0
else:
ratio = float('{:.2f}'.format(stats[i]['victories']/stats[i]['defeats']*100))
result_message += f"\n{stats[i]['name']}" \
f"{skip*(32-len(stats[i]['name'])-len(str(stats[i]['victories'])))}{stats[i]['victories']}" \
f"{skip*(16-len(str(stats[i]['defeats'])))}{stats[i]['defeats']}" \
f"{skip*(11-len(str(ratio)))}{ratio}" \
f"%{skip*7}{stats[i]['max_points']}\n"
await ctx.send(
f'**{skip*15}?Статистика казино?**\n**Игрок{skip*50}'
f'Побед{skip*12}Поражений{skip*9}%Побед{skip*14}Максимальный выйгрыш**\n```{result_message}```')
else:
await ctx.send("**❌ В этом канале мы не можем просматривать статистику! ❌**")
#Developer's tools
@bot.command()
@commands.cooldown(1, 60)
async def change_bet_winning(ctx, value: int):
await ctx.channel.purge(limit=1)
author = ctx.message.author
if ctx.message.author.guild_permissions.administrator:
bot.bet_winning = value
if value == -1:
await ctx.send(f"**Ограничение выйгрыша отключено❗️**")
else:
await ctx.send(f"**Ограничение выйгрыша при ставке в виде числа будет действовать, если на балансе "
f"меньше *{value}.*** ?")
else:
await ctx.send(f"**{author.mention}, откуда такую команду узнал, А?! ?**")
@change_bet_winning.error
async def change_bet_winning_error(ctx, error):
await ctx.send(f"**{ctx.message.author.mention}, на что менять-то? ?**")
@bot.command()
@commands.cooldown(1, 60 * 5)
async def bet_input_edit(ctx, value: int, procent: str = None):
await ctx.channel.purge(limit=1)
author = ctx.message.author
if author.guild_permissions.administrator:
casino_channel = bot.get_channel(bot.casino_channel)
if value > 100 and procent is None:
bot.bet_input = value
await casino_channel.send(f"**Ставка в казино изменена на *{value}! ⚙️***")
elif 0 < value < 100 and procent is None:
await ctx.send(f"**Ставка слишком мала!**")
elif value == -1:
await casino_channel.send(f"**Ставка в казино изменена на *максимальную! ?***")
elif procent == "%" and 0 < value < 100:
bot.bet_input = value / 100
await casino_channel.send(f"**Ставка в казино изменена на *{value}% от баланса ⚙️***")
else:
await ctx.send(f"**Введите корректное значение!***")
else:
await ctx.send(f"**{author.mention}, откуда такую команду узнал, А?! ?**")
@bet_input_edit.error
async def bet_input_edit_error(ctx, error):
await ctx.send(f"**{ctx.message.author.mention}, какой максимум для ставки? ?**")
@bot.command()
@commands.cooldown(1, 60*60)
async def reset_all_stats(ctx):
await ctx.channel.purge(limit=1)
if ctx.message.author.guild_permissions.administrator:
stats = {}
with open('casino_stats.py', 'wb') as out:
pickle.dump(stats, out)
await ctx.send(f"**Статистика была полностью очищена {ctx.message.author.mention}. ?**")
else:
await ctx.send(f"**{ctx.message.author.mention}, откуда такую команду узнал, А?! ?**")
@bot.command()
@commands.cooldown(1, 1.5)
async def add_stats(ctx, target: discord.User):
await ctx.channel.purge(limit=1)
casino_channel = bot.get_channel(bot.casino_channel)
if ctx.message.author.guild_permissions.administrator:
with open('casino_stats.py', 'rb') as inp:
stats = pickle.load(inp)
if target.id == 1010484897120534529:
await ctx.send(f"**{ctx.message.author.mention}, дебил⁉️**")
return False
if str(target.id) not in stats:
new_user = {'name': str(target), 'victories': 0, 'defeats': 0, 'points': 5000, 'max_points': 0}
stats[str(target.id)] = new_user
with open('casino_stats.py', 'wb') as out:
pickle.dump(stats, out)
await casino_channel.send(f"**{target.mention} был добавлен в статистику. ?**")
else:
await ctx.send(f"**{target.mention} уже имеет статистику. ?**")
else:
await ctx.send(f"**{ctx.message.author.mention}, откуда такую команду узнал, А?! ?**")
@add_stats.error
async def add_stats_error(ctx, error):
await ctx.send(f"**{ctx.message.author.mention}, кого-кого добавить в статистику? ?**")
@bot.command()
@commands.cooldown(1, 1.5)
async def ban(ctx, target: discord.User, ban_time: int, type: str, *, reason: str):
await ctx.channel.purge(limit=1)
casino_channel = bot.get_channel(bot.casino_channel)
if ctx.message.author.guild_permissions.administrator:
author = ctx.message.author
with open('ban_list.py', 'rb') as inp:
bans = pickle.load(inp)
if target.id == 1010484897120534529:
await ctx.send(f"**{ctx.message.author.mention}, дебил⁉️**")
return False
if str(target.id) in bans:
await ctx.send(f"**{target.mention} уже получил пиздюлей! ?**")
else:
if type == "m":
if ban_time > 1440:
await ctx.send(f"**{author.mention}, слишком большой срок для засранца. ?**")
return False
ban_time *= 60
if type == "h":
if ban_time > 24:
await ctx.send(f"**{author.mention}, слишком большой срок для засранца. ?**")
return False
ban_time *= 3600
if type == "s":
if ban_time > 86400:
await ctx.send(f"**{author.mention}, слишком большой срок для засранца. ?**")
return
bulshit = {'name': str(target), 'time_from': time.time(), 'ban_time': ban_time, 'type': type,
'reason': reason}
bans[str(target.id)] = bulshit
with open('ban_list.py', 'wb') as out:
pickle.dump(bans, out)
if type == "m":
await casino_channel.send(f"**{author.mention} забанил {target.mention} на *{int(ban_time/60)}* минут по причине:"
f" *{reason}!*** ?")
elif type == 'h':
await casino_channel.send(f"**{author.mention} забанил {target.mention} на *{int(ban_time/3600)} часов* по причине"
f": *{reason}!*** ?")
else:
await casino_channel.send(f"**{author.mention} забанил {target.mention} на *{ban_time} секунд* по причине: "
f"*{reason}!*** ?")
else:
await ctx.send(f"**{ctx.message.author.mention}, банить решил, падла?! А?! ?**")
@ban.error
async def ban_error(ctx, error):
await ctx.send(f"**{ctx.message.author.mention}, бан кого-то, на сколько-то, в каком времени, по причине! ?**")
@bot.command()
@commands.cooldown(1, 1.5)
async def unban(ctx, target: discord.User):
await ctx.channel.purge(limit=1)
casino_channel = bot.get_channel(bot.casino_channel)
if ctx.message.author.guild_permissions.administrator:
author = ctx.message.author
with open('ban_list.py', 'rb') as inp:
bans = pickle.load(inp)
if target.id == 1010484897120534529:
await ctx.send(f"**{ctx.message.author.mention}, дебил⁉️**")
return False
if str(target.id) not in bans:
await ctx.send(f"**{target.mention} нет в списках иродов! ❌**")
return False
bans.pop(str(target.id))
with open('ban_list.py', 'wb') as out:
pickle.dump(bans, out)
await casino_channel.send(f"**{author.mention} разбанил {target.mention}! ⭕️**")
else:
await ctx.send(f"**{ctx.message.author.mention}, банить решил, падла?! А?! ?**")
@unban.error
async def unban_error(ctx, error):
await ctx.send(f"**{ctx.message.author.mention}, кого-кого разбанить? А зачем? ?**")
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
author = ctx.message.author
retry_after = str(datetime.timedelta(seconds=error.retry_after)).split('.')[0]
await ctx.send(f'**{author.mention}, используй команду через {retry_after}** ?')
token = settings['token']
try:
bot.run(token)
except:
os.system("kill 1")
#bot.run(token) # Обращаемся к словарю settings с ключом token, для получения токена
Если я не использую эту часть кода:
try:
bot.run(token)
except:
os.system("kill 1")
У меня появляется ошибка:
Traceback (most recent call last):
File "/home/container/casino.py", line 836, in <module>
bot.run(token) # Обращаемся к словарю settings с ключом token, для получения токена
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 828, in run
asyncio.run(runner())
File "/usr/local/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 641, in run_until_complete
return future.result()
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 745, in start
await self.login(token)
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 580, in login
data = await self.http.static_login(token)
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 801, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 680, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0):
Помогите, пожалуйста! Никак не могу понять, в чём же проблема :{
Ответы (1 шт):
Автор решения: BlackCoder
→ Ссылка
написано же enable cookies, включи куки значит, дискорд тебя забанил по айпи, если бан не спадет юзай прокси
