After #bot event other commands do not work - discord

I have code like this:
#bot.command(pass_context=True)
#commands.has_any_role(admin, moderator, ghostluko)
async def ver(ctx,member:discord.Member = None):
role = ctx.guild.get_role(role_id=868210259284619324)
role1 = ctx.guild.get_role(role_id=905358001270046770)
await ctx.message.delete()
await member.add_roles(role)
await member.remove_roles(role1)
await ctx.send(f'{member} дал роль "{role}"')
after I add this, other commands start do not work
#bot.event
async def on_message(message):
embedbotreply = discord.Embed(description = f"Напишите help для подробной информации. Ваш префикс: {bot.command_prefix}", color = 0x8147fc)
if bot.user.mentioned_in(message):
await message.channel.send(embed = embedbotreply)
#bot.command()
async def ping(ctx):
embedping = discord.Embed(description = f" Мой пинг: {format(round(bot.latency, 1))} ms!", color = 0x8147fc)
await ctx.send(embed = embedping)
await ctx.message.delete()
Also, on_member_join do not work. I don't know what to do.

#bot.event
async def on_message(message):
if message.author==bot.user:
return
await bot.process_commands(message)
Try using await bot.process_commands(message) in your code and after this code you can use your other commands :
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
print('We are logged in!')
#bot.event
async def on_message(message):
if message.author==bot.user:
return
await bot.process_commands(message)
#bot.command()
async def ping(message) :
await message.channel.send("Pong!!")
bot.run("TOKEN")
Hope, this helps you !!

Related

data from telegram bot is not saving using sqlite3

I'm developing a telegram bot to register user and save his data in db. And after the registration I can't see that data in sqlite3. I don't understand what`s the problem and how to fix it
async def db_start():
global db, cur
db = sq.connect('base.db')
cur = db.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS members(user_id TEXT PRIMARY KEY, name TEXT, phone TEXT, email TEXT, about TEXT, post TEXT, letters TEXT, box TEXT, donate TEXT)")
db.commit()
async def register(user_id):
user = cur.execute("SELECT 1 FROM members WHERE user_id == '{key}'".format(key=user_id)).fetchone()
if not user:
cur.execute("INSERT INTO members VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)", (user_id, '', '', '', '', '', '', '', ''))
db.commit()
async def update(state, user_id):
async with state.proxy() as data:
cur.execute("UPDATE members SET name = '{}', phone = '{}', email = '{}', about = '{}', post = '{}', letters = '{}', box = '{}', donate = '{}' WHERE user_id == '{}'".format(data['name'], data['phone'], data['email'], data['about'], data['post'], data['letters'], data['box'], data['donate'], user_id))
db.commit()
Here is the db screens
db screen from sqlite3 db screen from pycharm
code from the main file
async def on_startup(_):
await db_start()
storage = MemoryStorage()
bot = Bot(token=config.TOKEN)
dp = Dispatcher(bot, storage=storage)
class ProfileStatesGroup(StatesGroup):
name = State()
phone = State()
email = State()
about = State()
post = State()
letters = State()
box = State()
donate = State()
def get_kb() -> ReplyKeyboardMarkup:
kb = ReplyKeyboardMarkup(resize_keyboard=True)
kb.add(KeyboardButton('/register'))
return kb
def get_cancel_kb() -> ReplyKeyboardMarkup:
kb = ReplyKeyboardMarkup(resize_keyboard=True)
kb.add(KeyboardButton('/cancel'))
return kb
#dp.message_handler(commands=['cancel'], state='*')
async def cmd_cancel(message: types.Message, state: FSMContext):
if state is None:
return
await state.finish()
await message.reply('text',
reply_markup=get_kb())
#dp.message_handler(commands=['start'])
async def cmd_start(message: types.Message) -> None:
await message.answer("text", reply_markup=get_kb())
await register(user_id=message.from_user.id)
#dp.message_handler(commands=['register'])
async def cmd_create(message: types.Message) -> None:
await message.reply("text",
reply_markup=get_cancel_kb())
await ProfileStatesGroup.next()
# await ProfileStatesGroup.name.set()
#dp.message_handler(state=ProfileStatesGroup.name)
async def load_name(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['name'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.phone)
async def load_phone(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['phone'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.email)
async def load_email(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['email'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.about)
async def load_about(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['about'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.post)
async def load_post(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['post'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.letters)
async def load_letters(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['letters'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.box)
async def load_box(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['box'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.donate)
async def load_donate(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['donate'] = message.text
await update(state, user_id=message.from_user.id)
await message.reply("text")
await state.finish()
I will be very grateful if somebody helps me to find my problem :)

Commands not working from discord.ext import commands

So basically I have this problem, any command that I type does not work. There are no errors, and everything else is working fine. It's just that for some reasons #bot.command() isn't working, and that is kind of annoying.
import discord
from discord.utils import get
from discord.ext import commands
import time
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix = '$', intents=intents)
TOKEN = 'hi'
ROLE = 'hi'
db1 = [hi, hi]
#bot.command()
async def test(ctx, arg):
await ctx.send(arg)
await bot.process_commands(arg)
#bot.event
async def on_member_join(member):
role = get(member.guild.roles, name=ROLE)
await member.add_roles(role)
await member.send('hi')
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="Cheapest coins on the market", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="Cheapest coins on the market", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_member_remove(member):
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_invite_create(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been created, {}, by <#{}> on {}".format(str(invite.url), str(invite.inviter.id), str(invite.created_at)))
#bot.event
async def on_invite_delete(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been deleted by{}".format(str(invite.inviter.id)))
#bot.event
async def on_member_ban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Ban", description="Ban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_member_unban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Unban", description="Unban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_ready():
print(f'{bot.user} succesfully logged in')
return
#bot.event
async def on_message(message):
if message.content.startswith('purge requested by'):
time.sleep(1)
await message.delete()
if message.author == bot:
return
if message.content == 'hi':
await message.channel.send('hi')
if message.content.startswith('binvites'):
totalInvites = 0
for i in await message.guild.invites():
if i.inviter == message.author:
totalInvites += i.uses
await message.channel.send(f"You have invited {totalInvites} member{'' if totalInvites == 1 else 's'} to the Central Trade server")
if message.content == 'bpurge':
if message.author.id in db1:
await message.channel.purge(limit=10)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
else:
return
if message.content == 'block':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = False
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Lock", description="Channel lock request by <#{}>".format(str(message.author.id)), color= 0x00FFFF)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'bunlock':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = True
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Unlock", description="Channel unlock request by <#{}>".format(str(message.author.id)), color=0xC0C0C0)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'test':
embedVar = discord.Embed(title="test", description="test", color=0x00ff00)
embedVar.add_field(name="test", value="test", inline=False)
embedVar.add_field(name="test", value="test", inline=False)
await message.channel.send(embed=embedVar)
if message.content == 'bpurges':
if message.author.id in db1:
await message.channel.purge(limit=10000)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
embedVar = discord.Embed(title="Purge", description="Purge requested by<#{}>".format(str(message.author.id)))
await message.channel.send(embed=embedVar)
time.sleep(1)
await message.channel.delete()
bot.run(TOKEN)
Anyone has an idea why it's not working ?
Also seems like i need to post more details, don't pay attention to this :
Roméo et Juliette (Romeo and Juliet) est une tragédie de William Shakespeare.

See who invited a discord bot (js)

I would like to log when my bot joins servers (i already have the base code) I just need to know how to define the owner of the server! if you know how to do this please help me!
Well, from the "guildCreate" event, you recieve a Guild class. From which you can access the owner GuildMember class. Then you can get the information about the owner that.
Here is an example:
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("guildCreate", (guild) => {
console.log(`I have been added to a new guild! ${guild.name}
Owner name: ${guild.owner.user.username}`);
})
client.login("yourToken")
It's the best to read thru the docs.
For checking who invited :
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("guildCreate", async guild => {
const fetchedLogs = await guild.fetchAuditLogs({
limit: 1,
type: "BOT_ADD"
});
const auditlog = fetchedLogs.entries.first();
let myChannel = client.channels.cache.find(channel => channel.id == YOUR_CHANNEL_ID);
myChannel.send(auditlog.executor.tag + " added bot in "+ guild.name+"\nOwner is:
"guild.owner.user.username);
});
Also you can check for VIEW_AUDIT_LOGS permission

My reaction roles command won't work in Discord.js v12

Ok so... I've been attempting to make a reaction roles command but it won't work. The role isn't given to the user. It gives me this error "ReferenceError: reaction is not defined"
Code:
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL","REACTION"]});
client.on('message', async message => {
if(message.content === '>reactions'){
const embed = new Discord.MessageEmbed()
.setTitle('Reaction Roles')
.setDescription('React to obtain your roles!')
.setColor('#242323')
let MessageEmbed = await message.channel.send(embed)
MessageEmbed.react('👨‍👦')
}
if(reaction.message.partial) await reaction.message.fetch();
if(reaction.partial) await reaction.fetch();
if(user.client) return;
if(!reaction.message.guild) return;
if(reaction.message.channel.id === "759064796611215442") {
if(reaction.emoji.name === '👨‍👦'){
await reaction.message.guild.member.cache.get(user.id).roles.add('760838222057046046')
}
}
});

Discord Python Rewrite - wait_for('reaction_add')

so, im trying to make a reaction help with this code
#client.command()
async def test(ctx):
msg = await ctx.send("Eh idk just react")
await msg.add_reaction("⬅️")
await msg.add_reaction("➡️")
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji) in ['⬅️', '➡️']
try:
reaction, user = await client.wait_for('reaction_add', timeout=5, check=check)
if reaction == '➡️':
await ctx.send("NEEXT!")
return
elif reaction == '⬅️':
await ctx.send("RETUUURN!")
return
except asyncio.TimeoutError:
await ctx.send("Timed out")
but when a reaction added, it dosen't do anything. Can someone help me? I want reaction help for 1week.
You need to use reaction.emoji when comparing to unicode emojis.
#client.command()
async def test(ctx):
msg = await ctx.send("Eh idk just react")
await msg.add_reaction("⬅️")
await msg.add_reaction("➡️")
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji) in ['⬅️', '➡️']
try:
reaction, user = await client.wait_for('reaction_add', timeout=5, check=check)
if reaction.emoji == '➡️':
await ctx.send("NEEXT!")
return
elif reaction.emoji == '⬅️':
await ctx.send("RETUUURN!")
return
except asyncio.TimeoutError:
await ctx.send("Timed out")

Resources