Hello everyone I wrote a bot for a freelance tutorial order, the bot responds to messages, but there is a problem with payment, after entering the amount of replenishment, the bot does not respond, maybe I made a mistake somewhere?
main.py code
import logging
from aiogram import Bot, Dispatcher, executor, types
import config as cfg
import markups as nav
logging.basicConfig(level=logging.INFO)
import logging
from aiogram import Bot, Dispatcher, executor, types
import config as cfg
import markups as nav
from db import Database
from pyqiwip2p import QiwiP2P
import random
logging.basicConfig(level=logging.INFO)
bot = Bot(token=cfg.TOKEN)
dp = Dispatcher(bot)
db = Database("database.db")
p2p = QiwiP2P(auth_key=cfg.QIWI_TOKEN)
def is_number(_str):
try:
int(_str)
return True
except ValueError:
return False
#dp.message_handler(commands=['start'])
async def command_start(message: types.Message):
if message.chat.type == 'private':
if not db.user_exists(message.from_user.id):
db.add_user(message.from_user.id)
await bot.send_message(message.from_user.id, "Здравствуй дорогой {0.first_name}!\n\nТвой процент удачи сегодня: 99%\n"
f"\n💳Ваш баланс: {db.user_money(message.from_user.id)} руб".format(message.from_user), reply_markup=nav.mainMenu)
#dp.message_handler()
async def command_start(message: types.Message):
if message.text == 'ST':
await bot.send_message(message.from_user.id, '🕹️Купить читы')
elif message.text == '🕹️Купить читы':
await bot.send_message(message.from_user.id, '🤖Выберите игру!', reply_markup = nav.ChFoGaMeMenu)
elif message.text == '📰Hot Новости':
await bot.send_message(message.from_user.id, '🤖Выберите дату!', reply_markup = nav.newsMenu)
elif message.text == '🔥️Лайфхаки дня':
await bot.send_message(message.from_user.id, '🤖Выберите жанр игры!', reply_markup=nav.LiHaMenu)
elif message.text == '🤖О боте':
await bot.send_message(message.from_user.id, '🤖Хоешь узнать обо мне?!', reply_markup=nav.aboutthebotMenu)
elif message.text == '👤Профиль':
await bot.send_message(message.from_user.id, '💬Ваш аккаунт'.format(message.from_user), reply_markup=nav.myaccMenu)
elif message.text == '🔙Главное меню':
await bot.send_message(message.from_user.id, '🔙Вы в главном меню', reply_markup=nav.mainMenu)
#Читы для игр
elif message.text == '🎁CS-GO':
await bot.send_message(message.from_user.id, '\n💳Оплатить товар [🎁CS-GO] 110₽'
'\n'
'\n💰Оплата Qiwi/Сбер/Тинькофф', reply_markup=nav.buyCSMenu)
elif message.text == '🎁Dota2':
await bot.send_message(message.from_user.id, '\n💳Оплатить товар [🎁Dota2] 110₽'
'\n'
'\n💰Оплата Qiwi/Сбер/Тинькофф', reply_markup=nav.buyDota2Menu)
elif message.text == '🎁Call Of Duty:Black Ops':
await bot.send_message(message.from_user.id, '\n💳Оплатить товар [🎁Call Of Duty:Black Ops] 110₽'
'\n'
'\n💰Оплата Qiwi/Сбер/Тинькофф', reply_markup=nav.buyCallOfDutyMenu)
elif message.text == '🎁PUBG':
await bot.send_message(message.from_user.id, '\n💳Оплатить товар [🎁PUBG] 110₽'
'\n'
'\n💰Оплата Qiwi/Сбер/Тинькофф', reply_markup=nav.buyPUBGMenu)
elif message.text == '🎁Standoff2':
await bot.send_message(message.from_user.id, '\n💳Оплатить товар [🎁Standoff2] 110₽'
'\n'
'\n💰Оплата Qiwi/Сбер/Тинькофф', reply_markup=nav.buyStandoff2Menu)
elif message.text == '🔙Главное меню':
await bot.send_message(message.from_user.id, '🔙Вы в главном меню', reply_markup=nav.ChFoGaMeMenu)
#Новости для игр
elif message.text == '📋Today':
await bot.send_message(message.from_user.id, '📋Today', reply_markup=nav.newsTMenu)
elif message.text == '📋Yesterday':
await bot.send_message(message.from_user.id, '📋Yesterday', reply_markup=nav.newsYEMenu)
elif message.text == '🔙Главное меню':
await bot.send_message(message.from_user.id, '🔙Вы в главном меню', reply_markup=nav.ChFoGaMeMenu)
#Лайфхак для игр
elif message.text == '🔥Шутеры':
await bot.send_message(message.from_user.id, '🔥Лайфхаки для [Шутеров] читай в Telegraph', reply_markup=nav.newsShootMenu)
elif message.text == '🔥ММОРПГ':
await bot.send_message(message.from_user.id, '🔥Лайфхаки для [ММОРПГ] читай в Telegraph', reply_markup=nav.newsMMORPGMenu)
elif message.text == '🔥Стратегии':
await bot.send_message(message.from_user.id, '🔥Лайфхаки для [Стратегии] читай в Telegraph', reply_markup=nav.newsStrategyMenu)
elif message.text == '🔥MMO Action[скоро!]':
await bot.send_message(message.from_user.id, '🔥Лайфхаки для [MMO Action] читай в Telegraph', reply_markup=nav.newsMMOActionMenu)
elif message.text == '🔙Главное меню':
await bot.send_message(message.from_user.id, '🔙Вы в главном меню', reply_markup=nav.ChFoGaMeMenu)
#О боте для игр
elif message.text == '🤖Кто я?':
await bot.send_message(message.from_user.id, '🤖Основная информация о боте указана в telegraph!', reply_markup=nav.newsWhoiambMenu)
elif message.text == '📄Соглашение':
await bot.send_message(message.from_user.id, '📄Основная информация о пользовательском соглашении указана в telegraph!', reply_markup=nav.newsSoglbMenu)
elif message.text == '🔙Главное меню':
await bot.send_message(message.from_user.id, '🔙Вы в главном меню', reply_markup=nav.ChFoGaMeMenu)
#Профиль игрока
elif message.text == '💥Главное':
await bot.send_message(message.from_user.id, '\n💬Ваш аккаунт: {0.first_name}'
'\n'
'\n🧾Количество покупок: '
'\n'
f'\n💳Ваш баланс: {db.user_money(message.from_user.id)} руб.'.format(message.from_user), reply_markup=nav.myaccMenu)
elif message.text == '🧾Мои покупки':
await bot.send_message(message.from_user.id, '\n🧾Ваши покупки: '.format(message.from_user), reply_markup=nav.myaccMenu)
elif message.text == '💳Баланс':
await bot.send_message(message.from_user.id, f'\n💳Ваш баланс: {db.user_money(message.from_user.id)} руб.'.format(message.from_user), reply_markup=nav.topUpMenu)
elif message.text == '🔙Главное меню':
await bot.send_message(message.from_user.id, '🔙Вы в главном меню', reply_markup=nav.ChFoGaMeMenu)
#dp.message_handler()
async def bot_mess(message: types.Message):
if is_number(message.text):
message_money = int(message.text)
if message_money >= 5:
comment = str(message.from_user.id) + "_" + str(random.randint(1000, 9999))
bill = p2p.bill(amount=message_money, lifetime=15, comment=comment)
db.add_check(message.from_user.id, message_money, bill.bill_id)
await bot.send_message(message.from_user.id, f"Вам нужно отправить {message_money} руб. на наш счет QIWI\nСсылку: {bill.pay_url}\nУказав комментарий к оплате: {comment}", reply_markup=nav.buy_menu(url=bill.pay_url, bill=bill.bill_id))
else:
await bot.send_message(message.from_user.id, "Минимальная сумма для пополнения 5 руб.")
else:
await bot.send_message(message.from_user.id, "Введите целое число")
#dp.callback_query_handler(text="top_up")
async def top_up(callback: types.CallbackQuery):
await bot.delete_message(callback.from_user.id, callback.message.message_id)
await bot.send_message(callback.from_user.id, "Введите сумму для пополнения!")
#dp.callback_query_handler(text_contains="check_")
async def check(callback: types.CallbackQuery):
bill = str(callback.data[6:])
info = db.get_check(bill)
if info != False:
if str(p2p.check(bill_id=bill).status) == "PAID":
user_money = db.user_money(callback.from_user.id)
money = int(info[2])
db.set_money(callback.from_user.id, user_money+money)
await bot.send_message(callback.from_user.id, "Ваш счет пополнен! Напишите /start")
db.delete_check(bill)
else:
await bot.send_message(callback.from_user.id, "Вы не оплатили счет!", reply_markup=nav.buy_menu(False, bill=bill))
else:
await bot.send_message(callback.from_user.id, "Счет не найден")
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
config.py code
TOKEN = "MyToken"
QIWI_TOKEN = "MyToken"
murkaps.py code
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
btnMain = KeyboardButton('🔙Главное меню')
# ---Main Menu---
btnBuyCheat = KeyboardButton('🕹️Купить читы')
btnNews = KeyboardButton('📰Hot Новости')
btnLifeHack = KeyboardButton('🔥️Лайфхаки дня')
btnMyacc = KeyboardButton('👤Профиль')
btnAboutTheBot = KeyboardButton('🤖О боте')
mainMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnBuyCheat, btnNews, btnLifeHack, btnMyacc, btnAboutTheBot)
btnTopUp = InlineKeyboardButton(text="Пополнить", callback_data="top_up")
topUpMenu = InlineKeyboardMarkup(row_width=1)
topUpMenu.insert(btnTopUp)
# ---Cheat For Game Menu---
btnCSGO = KeyboardButton('🎁CS-GO')
btnDota2 = KeyboardButton('🎁Dota2')
btnCODBO = KeyboardButton('🎁Call Of Duty:Black Ops')
btnPUBG = KeyboardButton('🎁PUBG')
btnST2 = KeyboardButton('🎁Standoff2')
ChFoGaMeMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnCSGO, btnDota2, btnCODBO, btnPUBG, btnST2, btnMain)
# ---Cheat For Game Menu---
btnToday = KeyboardButton('📋Today')
btnYetday = KeyboardButton('📋Yesterday')
newsMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnToday, btnYetday, btnMain)
# ---Lifehack for Game Menu---
btnShoot = KeyboardButton('🔥Шутеры')
btnMMORPG = KeyboardButton('🔥ММОРПГ')
btnStrateg = KeyboardButton('🔥Стратегии')
btnMMOA = KeyboardButton('🔥MMO Action[скоро!]')
LiHaMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnShoot, btnMMORPG, btnStrateg, btnMMOA, btnMain)
# ---About The Bot Menu---
btnWhoiam = KeyboardButton('🤖Кто я?')
btnSogl = KeyboardButton('📄Соглашение')
aboutthebotMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnWhoiam, btnSogl, btnMain)
# ---Buy Cheat For 🎁CS-GO Menu---
btnCSBuy = KeyboardButton('💳Оплатить\n[🎁CS-GO]')
buyCSMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnCSBuy, btnMain)
# ---Buy Cheat For 🎁Dota2 Menu---
btnDota2Buy = KeyboardButton('💳Оплатить\n[🎁Dota2]')
buyDota2Menu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnDota2Buy, btnMain)
# ---Buy Cheat For 🎁Call Of Duty:Black Ops Menu---
btnCallOfDutyBuy = KeyboardButton('💳Оплатить\n[🎁Call Of Duty:Black Ops]')
buyCallOfDutyMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnCallOfDutyBuy, btnMain)
# ---Buy Cheat For 🎁PUBG Menu---
btnPUBGBuy = KeyboardButton('💳Оплатить\n[🎁PUBG]')
buyPUBGMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnPUBGBuy, btnMain)
# ---Buy Cheat For 🎁Standoff2 Menu---
btnStandoff2Buy = KeyboardButton('💳Оплатить\n[🎁Standoff2]')
buyStandoff2Menu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnStandoff2Buy, btnMain)
# ---NewsToday Menu---
btnToday = KeyboardButton('📋Читать')
newsTMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnToday, btnMain)
# ---NewsYesterday Menu---
btnYesToday = KeyboardButton('📋Читать')
newsYEMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnYesToday, btnMain)
# ---🔥Шутеры Menu---
btnShoot = KeyboardButton('🔥Читать')
newsShootMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnShoot, btnMain)
# ---🔥ММОРПГ Menu---
btnMMORPG = KeyboardButton('🔥Читать')
newsMMORPGMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnMMORPG, btnMain)
# ---🔥Стратегии---
btnStrategy = KeyboardButton('🔥Читать')
newsStrategyMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnStrategy, btnMain)
# ---🔥MMO Action[скоро!] Menu---
btnMMOActionToday = KeyboardButton('🔥Читать')
newsMMOActionMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnMMOActionToday, btnMain)
# ---About Bot Menu---
btnWhoiamb = KeyboardButton('📋Читать')
newsWhoiambMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnWhoiamb, btnMain)
# ---Bot Agreement Menu---
btnSoglb = KeyboardButton('📋Читать')
newsSoglbMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnSoglb, btnMain)
# ---Profell Menu---
btnGlavn = KeyboardButton('💥Главное')
btnChek = KeyboardButton('🧾Мои покупки')
btnBalans = KeyboardButton('💳Баланс')
myaccMenu = ReplyKeyboardMarkup(resize_keyboard = True).add(btnGlavn, btnChek, btnBalans, btnMain)
# ---Popolnit Menu---
def buy_menu(isUrl = True, url="", bill=""):
qiwiMenu = InlineKeyboardMarkup(row_width=1)
if isUrl:
btnUrlQIWI = InlineKeyboardButton(text="Ссылка на оплату", url=url)
qiwiMenu.insert(btnUrlQIWI)
btnChekQIWI = InlineKeyboardButton(text="Проверить оплату", callback_data="check_"+bill)
qiwiMenu.insert(btnChekQIWI)
return qiwiMenu
db.py code
import _sqlite3
class Database:
def __init__(self, db_file):
self.connection = _sqlite3.connect(db_file)
self.cursor = self.connection.cursor()
def user_exists(self, user_id):
with self.connection:
result = self.cursor.execute("SELECT * FROM users WHERE 'user_id' = ?", (user_id,)).fetchall()
return bool(len(result))
def add_user(self, user_id):
with self.connection:
return self.cursor.execute("INSERT INTO users ('user_id') VALUES (?)", (user_id,))
def user_money(self, user_id):
with self.connection:
result = self.cursor.execute("SELECT money FROM users WHERE user_id = ?", (user_id,)).fetchmany(1)
return int(result[0][0])
def set_money(self, user_id, user_money):
with self.connection:
return self.cursor.execute("UPDATE 'users' SET money = ? WHERE 'user_id' = ?", (user_money, user_id))
def add_check(self, user_id, money, bill_id):
with self.connection:
return self.cursor.execute("INSERT INTO 'check' ('user_id', 'money', 'bill_id') VALUES (?,?,?)", (user_id, money, bill_id,))
def get_check(self, bill_id):
with self.connection:
result = self.cursor.execute("SELECT * FROM 'check' WHERE bill_id = ?", (bill_id,)).fetchmany(1)
if not bool(len(result)):
return False
return result[0]
def delete_check(self, bill_id):
with self.connection:
return self.cursor.execute("DELETE FROM `check` WHERE `bill_id` = ?", (bill_id,))
I could not find a solution to the problem, can someone tell me
Try using states:
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.dispatcher import FSMContext
from aiogram.contrib.fsm_storage.memory import MemoryStorage
dp = Dispatcher(bot, storage=MemoryStorage())
class Payment(StatesGroup):
wait_sum = State()
#dp.callback_query_handler(text="top_up")
async def top_up(callback: types.CallbackQuery):
await bot.delete_message(callback.from_user.id, callback.message.message_id)
await bot.send_message(callback.from_user.id, "Введите сумму для пополнения!")
await Payment.wait_sum.set()
#dp.message_handler(state=Payment.wait_sum)
async def bot_mess(message: types.Message, state: FSMContext):
#Your function for billing
#After user gave you the number:
await state.finish()
Related
#type: ignore
import os
from keep_alive import keep_alive
from discord.ext import commands
import discord
import asyncio
import datetime
import re
DC_TOK = os.environ['DC_TOK']
bot = commands.Bot(command_prefix='!', intents=discord.Intents(4194303))
#bot.event
async def on_message(msg: discord.Message):
if msg.author == bot.user:
return
guild = msg.guild
if msg.content == '!quack':
await msg.channel.send('''!ticket open subject - Creates a new ticket
**Ticket Support Team++**
!ticket close - Closes on-going ticket
!invite ping_message - Invites user to ticket
!remove ping_message - Removes user from ticket
!mark rank - Makes the ticket exclusive for specific rank
!category TITLE - Briefly categorises the ticket
''')
elif msg.content[:12] == '!ticket open':
chn = msg.channel
ticket_title = msg.content[13:]
if ticket_title.strip() == '':
ticket_title = 'None'
ticketer_acc = msg.author
ticketer = ticketer_acc.display_name
category = discord.utils.get(guild.categories, name="Tickets 2")
tcc = discord.utils.get(guild.channels, name="ticket-creation-logs")
elem = None
_ = None
async for mg in tcc.history():
if mg.content.startswith('CATEG'):
continue
elem, _ = mg.content.split(' ')
elem = int(elem)
_ = int(_)
break
assert (elem is not None)
elem += 1
await tcc.send(str(elem) + ' ' + str(msg.author.id))
tck_channel = await guild.create_text_channel(f'{elem}-{ticketer}',
category=category)
await tck_channel.set_permissions(ticketer_acc,
read_messages=True,
send_messages=True)
await chn.send(
f'**TICKET {elem}**\n\nYour ticket has been created. <#{tck_channel.id}>'
)
await tck_channel.send(
f'<#{ticketer_acc.id}> Hello emo! Your ticket has been created, subject: `{ticket_title}`.\nOur support team will be with you soon! Meanwhile please address your problem because those emos are really busy!!!'
)
elif msg.content == '!ticket close':
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
if not (discord.utils.get(guild.roles, name='Ticket support team')
in msg.author.roles or discord.utils.get(
guild.roles, name='Administrator') in msg.author.roles
or discord.utils.get(guild.roles,
name='Co-owners (A.K.A. super admin)')
in msg.author.roles or discord.utils.get(
guild.roles, name='Owner') in msg.author.roles):
return
closed_cat = discord.utils.get(guild.categories, name="Tickets 3")
nam = msg.channel.name.lstrip('🔱🛡️')
tick_id = int(nam[:nam.find('-')])
tcc = discord.utils.get(guild.channels, name="ticket-creation-logs")
elem = None
creator = None
async for mg in tcc.history():
if mg.content.startswith('CATEG'):
continue
elem, creator = mg.content.split(' ')
elem = int(elem)
creator = int(creator)
if elem == tick_id:
break
assert (elem is not None)
await msg.channel.send('Closing ticket...')
counter = {}
async for mg in msg.channel.history():
if mg.author.bot or mg.author.id == creator:
continue
if mg.author.id not in counter.keys():
counter[mg.author.id] = 1
else:
counter[mg.author.id] += 1
max_num = 0
max_authors = []
for key, value in counter.items():
if value > max_num:
max_num = value
max_authors = [key]
elif value == max_num:
max_authors.append(key)
user_ping_list = ' '.join([f'<#{usr}>' for usr in max_authors
]) + ' contributed the most.'
if user_ping_list == ' contributed the most.':
user_ping_list = 'No one contributed.'
await msg.channel.send(user_ping_list)
await msg.channel.send('We hope we were able to solve your problem.')
await asyncio.sleep(3)
tick_creator = discord.utils.get(guild.members, id=creator)
assert (tick_creator is not None)
await msg.channel.set_permissions(tick_creator, overwrite=None)
await msg.channel.edit(category=closed_cat)
dms = discord.utils.get(guild.members, id=creator)
assert (dms is not None)
DM = dms
dms = DM._user.dm_channel
if dms is None:
dms = await DM._user.create_dm()
del DM
cr = msg.channel.created_at
assert (cr is not None)
tick_created: datetime.datetime = cr.replace(tzinfo=None)
time_cur = datetime.datetime.utcnow().replace(tzinfo=None)
td = time_cur - tick_created
mm, ss = divmod(td.seconds, 60)
hh, mm = divmod(mm, 60)
timestr = ''
if td.days > 0:
timestr += f'{td.days}d '
if hh > 0:
timestr += f'{hh}h '
if mm > 0:
timestr += f'{mm}m '
if ss > 0:
timestr += f'{ss}s'
await dms.send(f'''Your ticket has been closed by <#{msg.author.id}>
Your ticket lasted `{timestr}`.
We hope we were able to solve your problem. :partying_face:''')
elif msg.content == '!mark co':
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
if not (discord.utils.get(guild.roles, name='Ticket support team')
in msg.author.roles or discord.utils.get(
guild.roles, name='Administrator') in msg.author.roles
or discord.utils.get(guild.roles,
name='Co-owners (A.K.A. super admin)')
in msg.author.roles or discord.utils.get(
guild.roles, name='Owner') in msg.author.roles):
return
await msg.channel.send('Requesting to mark this ticket for: `Co-owner`')
nam = msg.channel.name
if nam.startswith('🛡️'):
nam = nam[1:]
assert (nam is not None)
if nam.startswith('🔱'):
await msg.channel.send('Ticket already marked for `Co-owner`')
else:
await msg.channel.edit(name='🔱' + nam)
await msg.channel.send(
f'<#{msg.author.id}> marked this ticket for: `Co-owner`')
await msg.channel.send(':trident:')
elif msg.content == '!mark admin':
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
if not (discord.utils.get(guild.roles, name='Ticket support team')
in msg.author.roles or discord.utils.get(
guild.roles, name='Administrator') in msg.author.roles
or discord.utils.get(guild.roles,
name='Co-owners (A.K.A. super admin)')
in msg.author.roles or discord.utils.get(
guild.roles, name='Owner') in msg.author.roles):
return
await msg.channel.send(
'Requesting to mark this ticket for: `Administrator`')
nam = msg.channel.name
assert (nam is not None)
if nam.startswith('🛡️'):
await msg.channel.send('Ticket already marked for `Administrator`')
elif nam.startswith('🔱'):
await msg.channel.send('Ticket already marked for `Co-owner`')
else:
await msg.channel.edit(name='🛡️' + nam)
await msg.channel.send(
f'<#{msg.author.id}> marked this ticket for: `Adiministrator`')
await msg.channel.send(':shield:')
elif msg.content[:7] == '!invite':
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
if not (discord.utils.get(guild.roles, name='Ticket support team')
in msg.author.roles or discord.utils.get(
guild.roles, name='Administrator') in msg.author.roles
or discord.utils.get(guild.roles,
name='Co-owners (A.K.A. super admin)')
in msg.author.roles or discord.utils.get(
guild.roles, name='Owner') in msg.author.roles):
return
usr_ping = msg.content[8:]
if not (usr_ping.startswith('<#') and usr_ping.endswith('>')
and usr_ping[2:-1].isdigit()):
return
invited_usr = discord.utils.get(guild.members, id=int(usr_ping[2:-1]))
assert (invited_usr is not None)
await msg.channel.set_permissions(invited_usr,
read_messages=True,
send_messages=True)
await msg.channel.send(f'{usr_ping} was invited into the ticket.')
elif msg.content[:7] == '!remove':
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
if not (discord.utils.get(guild.roles, name='Ticket support team')
in msg.author.roles or discord.utils.get(
guild.roles, name='Administrator') in msg.author.roles
or discord.utils.get(guild.roles,
name='Co-owners (A.K.A. super admin)')
in msg.author.roles or discord.utils.get(
guild.roles, name='Owner') in msg.author.roles):
return
usr_ping = msg.content[8:]
if not (usr_ping.startswith('<#') and usr_ping.endswith('>')
and usr_ping[2:-1].isdigit()):
return
invited_usr = discord.utils.get(guild.members, id=int(usr_ping[2:-1]))
assert (invited_usr is not None)
await msg.channel.set_permissions(invited_usr, overwrite=None)
await msg.channel.send(f'{usr_ping} was removed from the ticket.')
elif msg.content[:9] == '!category':
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
if not (discord.utils.get(guild.roles, name='Ticket support team')
in msg.author.roles or discord.utils.get(
guild.roles, name='Administrator') in msg.author.roles
or discord.utils.get(guild.roles,
name='Co-owners (A.K.A. super admin)')
in msg.author.roles or discord.utils.get(
guild.roles, name='Owner') in msg.author.roles):
return
categ = msg.content[10:]
tcc = discord.utils.get(guild.channels, name="ticket-creation-logs")
nam = msg.channel.name.lstrip('🔱🛡️')
tick_id = int(nam[:nam.find('-')])
async for mg in tcc.history():
if mg.content.startswith(f'CATEG {tick_id}'):
await msg.channel.send(
f'''This ticket is already marked with category **{mg.content[len(f'CATEG{tick_id}')+2:]}**'''
)
return
await tcc.send(f'CATEG {tick_id} {categ}')
await msg.channel.send(
f'''<#{msg.author.id}> marked this ticket with category **{categ}**''')
else:
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
PING_PTN = '<#[0-9]+>'
pings = re.findall(PING_PTN, msg.content, re.UNICODE)
usrs = [
discord.utils.get(guild.members, id=int(ping[2:-1])) for ping in pings
]
remainder = msg.content
for ping in pings:
remainder = remainder.replace(str(ping), '')
for usr in usrs:
assert (usr is not None)
DM = usr
dms = DM._user.dm_channel
if dms is None:
dms = await DM._user.create_dm()
del DM
await dms.send(
f'''`{msg.author.name}#{msg.author.discriminator}`Pinged you in a ticket: <#{msg.channel.id}>
`{remainder}`''')
keep_alive()
bot.run(DC_TOK)
main.py
from flask import Flask
from threading import Thread
app = Flask('')
#app.route('/')
def home():
return "Hello. I am alive!"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
keep_alive.py
I am hosting my project on repl.it and using uptimerobot to ping it every 10 minutes so that it does not go dormant. But discord cloudflare bans it. I hear some say it's because of uptimerobot but how does that even affect the discord API? Also, the plan you give me must not require payment or payment methods of any type. I am a minor.
As moinierer3000 said,
Replit uses shared IPs to host your Discord bots.
This means that when you run your bots, it sends requests to Discord servers, that are proxies by Cloudflare that rate-limits how much requests an IP can make to defend the app from DDoS attacks.
I'd recommend you to just shutdown the bot, wait 15-30 minutes and try again later. I've done this numerous times and it worked great.
Hope this answer helped you.
This question has been solved
SOLUTION: find another cloud server because it is rate limited.
I'm trying to put my music discord bot on heroku hosting. the bot uses ffmpeg to play music. i have installed all the necessary buildpacks and still nothing helps. the bot just connects to the discord server and keeps silent.
I tried to install all the buildpacks that are advised, but nothing helps.
music-cog for the bot:
class music_cog(commands.Cog):
def __init__(self, bot):
self.bot = bot
#all the music related stuff
self.is_playing = False
self.is_paused = False
# 2d array containing [song, channel]
self.music_queue = []
self.YDL_OPTIONS = {'format':'bestaudio', 'ignoreerrors':'True'}
self.FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
self.vc = None
#searching the item on youtube
def search_yt(self, url):
songs = []
titles = []
thumbnail = []
webpage_url = []
duration = []
with YoutubeDL(self.YDL_OPTIONS) as ydl:
if (url.startswith('https:')):
info = ydl.extract_info(url, download=False)
else:
info = ydl.extract_info('ytsearch:'+url, download=False)
if 'entries' in info:
info = info['entries']
for i in info:
try:
songs.append(i['url'])
titles.append(i['title'])
thumbnail.append(i['thumbnail'])
webpage_url.append(i['webpage_url'])
duration.append(i['duration'])
except:
pass
else:
try:
songs.append(info['url'])
titles.append(info['title'])
thumbnail.append(info['thumbnail'])
webpage_url.append(info['webpage_url'])
duration.append(info['duration'])
except:
pass
return songs, titles, thumbnail, webpage_url, duration
def play_next(self):
if len(self.music_queue) > 0:
print('зашли в play')
self.is_playing = True
#get the first url
m_url = self.music_queue[0][0]['source']
#remove the first element as you are currently playing it
self.music_queue.pop(0)
print('перед плей')
self.vc.play(discord.FFmpegPCMAudio(m_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
print('после плей')
else:
self.is_playing = False
print(self.is_playing)
# infinite loop checking
async def play_music(self, ctx):
if len(self.music_queue) > 0:
print('зашли в play_music')
self.is_playing = True
duration = int(self.music_queue[0][0]["duration"]/60*100)/100
duration = str(duration).replace('.', ':')
embed = discord.Embed(title="Now playing", description = f"[{self.music_queue[0][0]['title']}]({self.music_queue[0][0]['webpage_url']})", color=0x00e8e4)
embed.set_thumbnail(url = self.music_queue[0][0]['thumbnail'])
embed.add_field(name = f'00:00 // {duration}',value = "** **", inline=True)
print('обложка поставлена')
await ctx.send(embed=embed)
print('обложка отправлена')
m_url = self.music_queue[0][0]['source']
#try to connect to voice channel if you are not already connected
if self.vc == None or not self.vc.is_connected():
print('коннект к каналу')
self.vc = await self.music_queue[0][1].connect()
#in case we fail to connect
if self.vc == None:
await ctx.send("Could not connect to the voice channel")
return
else:
await self.vc.move_to(self.music_queue[0][1])
#remove the first element as you are currently playing it
self.music_queue.pop(0)
print('play')
self.vc.play(discord.FFmpegPCMAudio(m_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
else:
self.is_playing = False
#commands.command(name="play", aliases=["p","playing"], help="Plays a selected song from youtube")
async def play(self, ctx, *args):
print('вызван play')
query = " ".join(args)
voice_channel = ctx.author.voice.channel
if voice_channel is None:
#you need to be connected so that the bot knows where to go
await ctx.send("Connect to a voice channel!")
elif self.is_paused:
self.vc.resume()
else:
try:
check_list = query.split('&')[1]
if(check_list.startswith('list=')):
await ctx.send('**Loading playlist** :repeat:')
except Exception as e:
print(e)
songs, titles, thumbnail, webpage_url, duration = self.search_yt(query)
print('получены песни')
if len(songs) == 0:
await ctx.send("Could not download the song. Incorrect format try another keyword. This could be due to playlist or a livestream format.")
elif len(songs) == 1:
print(songs)
print('найдено количество')
song = {'source': songs[0], 'title': titles[0], 'thumbnail': thumbnail[0], 'webpage_url':webpage_url[0], 'duration':duration[0]}
await ctx.send(f"Song **{song['title']}** added to the queue")
self.music_queue.append([song, voice_channel])
if self.is_playing == False:
print('запустили play')
await self.play_music(ctx)
else:
await ctx.send(f"**{len(songs)}** tracks added to queue")
for i in range(len(songs)):
song = {'source': songs[i], 'title': titles[i], 'thumbnail': thumbnail[i], 'webpage_url':webpage_url[i], 'duration':duration[i]}
self.music_queue.append([song, voice_channel])
if self.is_playing == False:
await self.play_music(ctx)
#commands.command(name="pause", help="Pauses the current song being played")
async def pause(self, ctx, *args):
if self.is_playing:
self.is_playing = False
self.is_paused = True
self.vc.pause()
elif self.is_paused:
self.is_paused = False
self.is_playing = True
self.vc.resume()
#commands.command(name = "resume", aliases=["r"], help="Resumes playing with the discord bot")
async def resume(self, ctx, *args):
if self.is_paused:
self.is_paused = False
self.is_playing = True
self.vc.resume()
#commands.command(name="skip", aliases=["s"], help="Skips the current song being played")
async def skip(self, ctx):
if self.vc != None and self.vc:
self.vc.stop()
#try to play next in the queue if it exists
await self.play_music(ctx)
#commands.command(name="queue", aliases=["q"], help="Displays the current songs in queue")
async def queue(self, ctx):
retval = ""
for i in range(0, len(self.music_queue)):
retval += self.music_queue[i][0]['title'] + "\n"
if retval != "":
await ctx.send(retval)
else:
await ctx.send("No music in queue")
#commands.command(name="clear", aliases=["c", "bin"], help="Stops the music and clears the queue")
async def clear(self, ctx):
if self.vc != None and self.is_playing:
self.vc.stop()
self.music_queue = []
await ctx.send("Music queue cleared")
#commands.command(name="leave", aliases=["disconnect", "l", "d", "stop"], help="Kick the bot from VC")
async def dc(self, ctx):
self.is_playing = False
self.is_paused = False
self.music_queue = []
await self.vc.disconnect()
requirements.txt:
discord.py==2.0.1
youtube_dl==2021.12.17
So I am having a problem. I am making a game where it eliminates you every 5 seconds by taking away your role. When it eliminates you it will DM you. But I am having trouble as some people have DMs off and when the bot tries to DM them it stops the whole process even with the except Exception block, I have tried everything. Is there anything I did wrong here?
from discord.ext import commands
import discord
import time
import datetime
import random
from setup import ROLEID
import asyncio
class Game(commands.Cog):
def __init__(self, client):
self.client = client
async def guessthenumber(self, ctx, channel):
embed = discord.Embed(title='Minigame!',description='Play this game to win immunity!\nI am thinking of a number, 1-20, first to guess it wins immunity for a round!')
await channel.send(embed=embed)
randnum = random.randint(1,20)
openstatus = 'yes'
await channel.send(randnum)
while openstatus == 'yes':
def check(m):
return ctx.author == m.author
msg = await self.client.wait_for('message', timeout=60.0, check=check)
if msg.content == str(randnum) and openstatus == 'yes':
embed=discord.Embed(title="Number has been guessed!",description=f'{msg.author.mention} has guessed the number!')
await channel.send(embed=embed)
openstatus = 'no'
immunes = []
immunes.append(msg.author)
async def choosekick(self, ctx, channel,list_of_players, role):
the_choices = []
listy = list_of_players
choice1 = random.choice(listy)
listy.remove(choice1)
choice2 = random.choice(listy)
the_choices.append(choice1)
the_choices.append(choice2)
embed = discord.Embed(title='Vote Save!',description = f'Choose one of the following people to save!\n{the_choices[0].mention} or {the_choices[1].mention}')
msg = await channel.send(embed=embed)
await msg.add_reaction('1️⃣')
await msg.add_reaction('2️⃣')
global t1
t1 = 0
global t2
t2 = 0
await asyncio.sleep(10)
async def on_raw_reaction_add(self,payload):
guild = discord.utils.find(lambda g: g.id==payload.guild_id,self.client.guilds)
if payload.emoji.name == '1️⃣':
t1 += 1
if payload.emoji.name == '2️⃣':
t2 +=1
if t1 > t2:
loser = t1
await channel.send(f"{the_choices[1].mention} has been voted out!")
list_of_players.remove[the_choices[1]]
await the_choices[1].remove_roles(role)
await the_choices[1].send('You have been eliminated from the game')
else:
loser = t2
await channel.send(f"{the_choices[0].mention} has been voted out!")
await the_choices[0].remove_roles(role)
await the_choices[0].send('You have been eliminated from the game!')
list_of_players.remove(the_choices[0])
#commands.command()
async def commence(self, ctx):
try:
guild = ctx.guild
role = guild.get_role(ROLEID)
channel = await guild. create_text_channel('Elimination Game')
await channel.set_permissions(ctx.guild.default_role, send_messages=False,view_channel=False)
await channel.set_permissions(role, send_messages=True,view_channel=True)
embed = discord.Embed(title = 'The game has been commenced!', description=f'{role.mention} The elimination process will start in two minutes. This game works as follows.\nA person is eliminated every 3 minutes however there will be minigames to gain immunity! Keep your eye out for them!')
list_of_players = []
await channel.send(embed=embed)
for member in guild.members:
if role in member.roles:
list_of_players.append(member)
list_of_players.remove(self.client.user)
if len(list_of_players) < 45:
skipterval = 1
else:
skipterval = len(list_of_players) // 45
divided_point = len(list_of_players)//4
og_list = len(list_of_players)-divided_point
while len(list_of_players) >og_list:
await asyncio.sleep(5)
print(skipterval)
for loser in range(0,skipterval):
print('ii')
holder = random.choice(list_of_players)
eliminated_player = holder
list_of_players.remove(eliminated_player)
await eliminated_player.remove_roles(role)
embed = discord.Embed(title = 'Elimination!',description=f'{eliminated_player.mention} has been eliminated out of the game!')
await channel.send(embed=embed)
await eliminated_player.send('You have been eliminated from the game!')
print('dones')
randgame = random.randint(1,2)
if randgame == 1:
await self.guessthenumber(ctx, channel)
nextgame = 2
elif randgame == 2:
await self.choosekick(ctx,channel,list_of_players,role)
nextgame = 1
og_list = len(list_of_players) //4 + len(list_of_players) //4
embed = discord.Embed(title='Game Resumed!',description='The game has been resumed eliminations are starting...')
await channel.send(embed=embed)
if nextgame==1:
self.guessthenumber(ctx,channel)
if nextgame==2:
self.choosekick(ctx,channel,list_of_players,role)
except Exception:
pass
def setup(client):
client.add_cog(Game(client))
Good afternoon, I'm making a python bot in the aiogram library. Faced a problem, I created two inline keyboards and I have two menu buttons, one button should call the first inline keyboard and the second the second. But at startup it turns out that only the keyboard that is called first in the code is called, that is, in my code, "inline_button_menu" is called first, and the second does not react anymore. Help solve the problem.
Here is my code:
# Создание кнопок инлайн ---------------------------------------------------------------------
inline_btn_1 = InlineKeyboardButton('Сьогодні', callback_data='btn1')
inline_btn_2 = InlineKeyboardButton('На неділі', callback_data='btn2')
inline_btn_3 = InlineKeyboardButton('У цьому місяці', callback_data='btn3')
inline_btn_4 = InlineKeyboardButton('Останні 3 новини', callback_data='btn4')
inline_btn_5 = InlineKeyboardButton('Свіжі новини', callback_data='btn5')
# Инициализация кнопок(инлайн) ------------------------------------------------------------------------------------------
inline_button_menu = InlineKeyboardMarkup(row_width=2).add(
inline_btn_1).add(inline_btn_2).add(inline_btn_3)
inline_button_menu_2 = InlineKeyboardMarkup(row_width=2).add(
inline_btn_4).add(inline_btn_5)
# Кнопки меню(инлайн) ---------------------------------------------------------------------------------------------------
#dp.message_handler()
async def menu_birthday(message: types.Message):
# await bot.send_message(message.from_user.id, message.text)
if message.text == 'Дні народження':
await message.reply("Виберіть як подивитися дні народження: ",
reply_markup=inline_button_menu)
#dp.message_handler()
async def menu_news(message: types.Message):
# await bot.send_message(message.from_user.id, message.text)
if message.text == 'Новини':
await message.reply("Виберіть як подивитися новини: ",
reply_markup=inline_button_menu_2)
#dp.callback_query_handler(lambda c: c.data == 'btn4') # --------------------------- Последние три новости
async def process_callback_button1(callback_query: types.CallbackQuery):
await bot.answer_callback_query(callback_query.id)
with open("news_dict.json") as file:
news_dict = json.load(file)
for k, v in sorted(news_dict.items())[-3:]:
news = f"{hlink(v['article_title'], v['article_url'])}"
await bot.send_message(callback_query.from_user.id, news)
#dp.callback_query_handler(lambda c: c.data == 'btn5') # --------------------------- Свежие новости
async def process_callback_button1(callback_query: types.CallbackQuery):
await bot.answer_callback_query(callback_query.id)
fresh_news = check_news_update()
if len(fresh_news) >= 1:
for k, v in sorted(fresh_news.items()):
news = f"{hlink(v['article_title'], v['article_url'])}"
await bot.send_message(callback_query.from_user.id, news)
else:
await bot.send_message(callback_query.from_user.id, 'Свіжих новин немає')
#dp.callback_query_handler(lambda c: c.data == 'btn1') # -------------------------------------- Дни рождения
async def process_callback_button1(callback_query: types.CallbackQuery):
await bot.answer_callback_query(callback_query.id)
await bot.send_message(callback_query.from_user.id, 'Day: ')
Maybe too late, but
in your code there are two message handlers without any filters, so all your messages handled by this handler:
async def menu_birthday(message: types.Message):
For example you could add second condition to first function:
#dp.message_handler()
async def menu_birthday(message: types.Message):
if message.text == 'Дні народження':
await message.reply("Виберіть як подивитися дні народження: ",
reply_markup=inline_button_menu)
elif message.text == 'Новини':
await message.reply("Виберіть як подивитися новини: ",
reply_markup=inline_button_menu_2)
or you could have 2 separate handlers with text filters like this:
#dp.message_handler(text='Дні народження')
async def menu_birthday(message: types.Message):
await message.reply("Виберіть як подивитися дні народження: ", reply_markup=inline_button_menu)
#dp.message_handler(text='Новини')
async def menu_news(message: types.Message):
await message.reply("Виберіть як подивитися новини: ", reply_markup=inline_button_menu_2)
{
"360782765890863114": {
"money": 100000000000233425,
"afk": 0
},
"364379179405410304": {
"money": -999999999999957884,
"afk": 0
},
"533112978195742721": {
"money": 0,
"afk": 0
}
I have a JSON file like this. I am trying to sort this file and make a rank command out of it.
This is my whole code
import discord
import asyncio
import json
import operator
import sys
from discord.ext import commands
class money:
def __init__(self, bot):
self.bot = bot
self.bot.loop.create_task(self.save_users())
with open(r"/Users/gim-eunjeong/Documents/빠끔봇/cogs/users.json", 'r') as f:
self.users = json.load(f)
async def save_users(self):
await self.bot.wait_until_ready()
while not self.bot.is_closed():
with open(r"/Users/gim-eunjeong/Documents/빠끔봇/cogs/users.json", 'w') as f:
json.dump(self.users, f, indent=4)
await asyncio.sleep(5)
lines = []
def extract_money(self ,json):
try:
# Also convert to int since update_time will be string. When comparing
# strings, "10" is smaller than "2".
return int(['member_id']['money'])
except KeyError:
return 0
lines.sort(key=extract_money, reverse=True)
#commands.command()
async def 돈추가(self, ctx, member:discord.Member = None):
member = ctx.author if not member else member
member_id = str(member.id)
if ctx.author.id == 360782765890863114:
await ctx.send('얼마를 줄거야?')
def money_check(m):
return m.content.isdigit()
money_check = await self.bot.wait_for('message', check=money_check)
self.users[member_id]['money'] += int(money_check.content)
embed = discord.Embed(color=member.color, timestamp=ctx.message.created_at)
embed.set_author(name=f"money = {member}", icon_url=self.bot.user.avatar_url)
embed.add_field(name="준 돈", value=int(money_check.content))
embed.add_field(name="총 돈", value=self.users[member_id]['money'])
await ctx.send(embed=embed)
else:
embed=discord.Embed(title="⚠ 주의", description="빠봇 오너만 사용 가능한 명령어입니다.",color=0xd8ef56)
await ctx.send(embed=embed)
#commands.command()
async def 돈제외(self, ctx, member:discord.Member = None):
member = ctx.author if not member else member
member_id = str(member.id)
if ctx.author.id == 360782765890863114:
await ctx.send('얼마를 뺄거야?')
def money_check(m):
return m.content.isdigit()
money_check = await self.bot.wait_for('message', check=money_check)
self.users[member_id]['money'] -= int(money_check.content)
embed = discord.Embed(color=member.color, timestamp=ctx.message.created_at)
embed.set_author(name=f"money = {member}", icon_url=self.bot.user.avatar_url)
embed.add_field(name="뺀 돈", value=int(money_check.content))
embed.add_field(name="총 돈", value=self.users[member_id]['money'])
await ctx.send(embed=embed)
else:
embed=discord.Embed(title="⚠ 주의", description="빠봇 오너만 사용 가능한 명령어입니다.",color=0xd8ef56)
await ctx.send(embed=embed)
#commands.command()
async def 돈지갑(self, ctx, member: discord.Member = None):
member = ctx.author if not member else member
member_id = str(member.id)
if not member_id in self.users:
await ctx.send("")
else:
embed = discord.Embed(color=member.color, timestamp=ctx.message.created_at)
embed.set_author(name=f"돈 = {member}", icon_url=self.bot.user.avatar_url)
embed.add_field(name="돈", value=self.users[member_id]['money'])
await ctx.send(embed=embed)
async def on_message(self, message):
# we do not want the bot to reply to itself
author_id = str(message.author.id)
if not author_id in self.users:
self.users[author_id] = {}
self.users[author_id]['money'] = 0
self.users[author_id]['afk'] = 0
if message.content.startswith('빠봇 돈줘'):
getmoney = random.randint(1, 10000)
await message.channel.send('{}원을 받았다고.'.format(getmoney))
self.users[author_id]['money'] += getmoney
if message.content.startswith('빠봇 숫자게임'):
await message.channel.send('얼마를 걸거야?')
def money_check(m):
return m.content.isdigit()
money_check = await self.bot.wait_for('message', check=money_check)
if int(money_check.content) > self.users[author_id]['money']:
await message.channel.send('현재 돈보다 많은 양을 걸었어')
elif int(money_check.content) < self.users[author_id]['money']:
self.users[author_id]['money'] -= int(money_check.content)
await message.channel.send('1~10 사이의 숫자를 맞춰봐')
def guess_check(m):
return m.content.isdigit()
guess = await self.bot.wait_for('message', check=guess_check)
answer = random.randint(1, 10)
print(answer)
if guess is None:
fmt = '너무 오래걸린다.. 걍 내가 말해야지 {}.'
await message.channel.send(fmt.format(answer))
return
if int(guess.content) == answer:
await message.channel.send('정답! 건 돈의 10배가 돌아왔다!')
self.users[author_id]['money'] += int(money_check.content)*10
else:
await message.channel.send('미안하지만 정답은 {}(이)라구.'.format(answer))
def setup(bot):
bot.add_cog(money(bot))


Money rank (embed) Top 10 users
1
#맥꾸 / 1437000₩
2
<#429549533731487754> / 833000₩
3
#잠시 왔습니댜 곧 다시 외출합니댜 ㅌㅌ / 628000₩
4
#맹구 / 554000₩
5
#TanzenT / 512000₩
6
#한설 / 492000₩
7
#사막여우 / 409900₩
8
<#365396996774952961> / 324000₩
9
<#461073040642670592> / 268000₩
10
#{《\하이루☆/》} / 262000₩
This is the expected data