I switched to cogs yesterday so my code looks cleaner. Since then, all commands have broken. If you send t!profile it will send the message twice. I figured out that the problem has something to with the filter that I created.
if getImmunityValue == 0:
for word in getWord:
if getMutedValue == 0:
message.content = message.content.lower()
if message.content.count(''.join(word)) > 0:
id = message.author.id
curs.execute('SELECT channelID FROM getchannel')
getChannelID = curs.fetchone()[0]
channel = self.client.get_channel(getChannelID)
curs.execute('SELECT strike FROM user WHERE userID = (%s)', (id,))
getstrike = curs.fetchone()[0]
curs.execute(f'UPDATE user SET strike = {getstrike + 1} WHERE userID = {id}')
db.commit()
await message.delete()
await message.channel.send(f'{message.author.mention} Bitte benutzte kein Schimpfwoerter. Falls du weiter machen solltest, wirst du gebannt oder gemutet!')
Embed = discord.Embed(
title=f'{getstrike}x strike(s) from {message.author}',
color=discord.Colour.red(),
timestamp=self.datetime.utcnow()
)
Embed.add_field(name='Blacklist Wort:', value=message.content, inline=False)
Embed.add_field(name='Channel-ID:', value=message.channel.id, inline=False)
Embed.add_field(name='Channel:', value=message.channel, inline=False)
await channel.send(embed=Embed)
await self.client.process_commands(message)
So the problem is the await self.client.process_commands(message) I don't know why, but that fixes it.
Related
I've done various searches both in the documentation and in stackoverflow and I haven't found the answer that solves my problem.
I started programming discord bots again after abandoning it about 2 years and unfortunately with the slash command I'm just having so many problems. I've been trying to create a clear command for 3 days and luckily it works... but I can't edit the message on my cooldown so that it continues to lower the seconds for 10 seconds before it deletes the message. I searched the documentation (precisely here) and found various answers... too bad no one actually helped me and always gave me this error
File "***", line 116, in clear_error
await ctx.message.edit(embed=embed)
^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'edit'
I then decided to use him and it gave me this error
discord.errors.InteractionResponded: This interaction has already been responded to before
I'm sure I should do something to make it edit the message always using interaction.response but I'm out of ideas...
code:
#app_commands.checks.cooldown(1, 600, key=lambda i: (i.user.id))
#tree.command(name = "clear", description = "Cancella gli ultimi messaggi inviati ", guild=discord.Object(id=guild_id))
async def clear(ctx, limit: int):
embed = discord.Embed(
color=0xa61022
)
if limit == 0:
embed.set_author(
name=f'Non puoi cancellare 0 messaggi!',
)
await ctx.response.send_message(embed=embed, delete_after=10.0)
embed = discord.Embed(
color=0x03c03c
)
if limit == 1:
embed.set_author(
name=f'Ho cancellato ufficialmente un messaggio!',
icon_url=f'{ctx.user.avatar}'
)
else:
embed.set_author(
name=f'Ho cancellato ufficialmente {limit} messaggi!',
icon_url=f'{ctx.user.avatar}'
)
await ctx.channel.purge(limit=limit)
await ctx.response.send_message(embed=embed, delete_after=10.0)
embed = discord.Embed(
color=0xFFD000
)
if limit == 1:
embed.set_author(
name=f'{ctx.user.name} ha cancellato un messaggio',
icon_url=f'{ctx.user.avatar}'
)
else:
embed.set_author(
name=f'{ctx.user.name} ha cancellato {limit} messaggi',
icon_url=f'{ctx.user.avatar}'
)
embed.add_field(
name='Messaggi cancellati da:',
value=f'{ctx.user.name}',
inline=True
)
embed.add_field(
name='Quantità:',
value=f'{limit}',
inline=True
)
embed.add_field(
name='Canale dove è stato eseguito il comando:',
value=f'{ctx.channel.mention}',
inline=True
)
await logs_moderazione.send(embed=embed)
#clear.error
async def clear_error(ctx, error):
i = 0
embed=discord.Embed(
color=0xa61022
)
if isinstance(error, app_commands.CommandOnCooldown):
cd = round(error.retry_after)
time = str(datetime.timedelta(seconds=cd))
embed = discord.Embed(
description=f"**Riprova tra `{time}`**",
color=0xa61022
)
embed.set_author(
name=f"Sei in cooldown!",
icon_url=ctx.user.avatar
)
await ctx.response.send_message(embed=embed, delete_after=10.0)
for i in range(8):
if isinstance(error, app_commands.CommandOnCooldown):
cd = round(error.retry_after)
time = str(datetime.timedelta(seconds=cd))
embed = discord.Embed(
description=f"**Riprova tra `{time}`**",
color=0xa61022
)
embed.set_author(
name=f"Sei in cooldown!",
icon_url=ctx.user.avatar
)
await ctx.response.edit_message(embed=embed)
Libraries I use: discord.py and datetine
global variable: logs_moderazione (is a channel)
the error comes from the last line but it's better to forward all the code. I would also like to understand how to reset the cooldown since I can't anymore.
EDIT: the ctx variable is actually interaction.
Your edit method is missing, declare the edit method:
async def edit(ctx):
message = await ctx.send('testing')
await asyncio.sleep(0.3)
await message.edit(content='v2')
I would appreciate if anyone out there could help me.
I wanted to code a bot for a esports team, which does have a ticket included, on pycharm on my computer actually everything works fine, but when i then want to host it on replit it doesnt work. I have made the ticket with discord-components and as the button is clicked, the bot thinks, but does never send the messege and goes on with the code. But on my other replit file I have another ticket, but that does work just fine.
Does someone have an idea what could have gone wrong?
#client.command()
async def tryout(ctx):
server = client.get_guild(879321194506121247)
tryouter = get(server.roles, name="Tryouter")
embed_tryout = discord.Embed(title="Tryout",
description="*Start your tryout right now, to join HOC-Esports and start your clash royale esports journey*",
color=discord.Color.from_rgb(244, 246, 246))
embed_tryout.add_field(name="What we offer:",
value="• 4-5 scrims per week\n• A good organised team with engaged managers\n• Custom HOC logo + banner",
inline=False)
embed_tryout.add_field(name="What we demand from you:",
value="• You are engaged to improve yourself\n• You aren't toxic",
inline=False)
embed_tryout.add_field(name="Informations to the tryout""Infos zum Tryout",
value=f"You will make a bo5 against a {tryouter.mention}, who will rate your skill decide if you fit in our team or not",
inline=False)
await ctx.send(embed=embed_tryout, components=[
[Button(label="🎫 start tryout", style=1, custom_id="button1")]
])
#client.event
async def on_button_click(interaction):
if interaction.custom_id == "button1":
pass
else:
return
guild = interaction.guild
tryouter = get(guild.roles, name="Tryouter")
category = client.get_channel(997078909071929434)
await interaction.send(content="You just started a tryout", ephemeral=True)
benutzer = str(interaction.user)
user_letters = len(benutzer)
username = benutzer[:user_letters - 4]
ticket_channel = await guild.create_text_channel(name=f"Tryout of {username}", category=category)
user = interaction.author
tryoutrole = get(guild.roles, name= "Tryout")
visitorrole = get(guild.roles, name="Besucher")
esports_role = get(guild.roles, id=917100410400014426)
await user.add_roles(tryoutrole)
await user.remove_roles(besucherrolle)
await ticket_channel.set_permissions(user, view_channel=True, read_message_history=True, read_messages=True,
add_reactions=True, embed_links=True, attach_files=True,
use_external_emojis=True)
await ticket_channel.send(
f"Welcome {interaction.user.mention}. You just started a tryout.\nA {tryouter.mention} will take care of you.\nPlease send meanwhile your friendlink and your profile right here\nIf you don't want to make the tryout anymore, just close the ticket.",
components=[
Button(label="🔒 close ticket", style=2, custom_id="button2")
])
interaction2 = await client.wait_for("button_click", check=lambda i: i.custom_id == "button2")
await interaction2.send(content="You just closed the ticket", ephemeral=True)
time.sleep(5)
await ticket_channel.delete()
await user.remove_roles(tryoutrole)
if esports_role in user.roles:
return
await user.add_roles(visiterrole)
Im trying to make a public bot, and i would want this ticket system witha logging channel it already has a logging channel but how can i modify this to make a command that sets the logging channel?
# --- Ticket Open ---
#client.command()
#commands.guild_only()
async def ticket(ctx):
if ctx.channel.type != discord.ChannelType.private:
channels = [str(channel) for channel in client.get_all_channels()]
if f'ticket-{ctx.author.id}' in channels:
await ctx.message.delete()
else:
ticket_channel = await ctx.guild.create_text_channel(f'ticket-{ctx.author.id}')
await ticket_channel.set_permissions(ctx.guild.default_role, send_messages=False, read_messages=False)
await ticket_channel.set_permissions(ctx.author, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)
embed = discord.Embed(color=10181046, description=f'Please enter the reason for this ticket, type `-close` if you want to close this ticket.')
embed.set_thumbnail(url='')
await ticket_channel.send(f'{ctx.author.mention}', embed=embed)
await ctx.message.delete()
logchannel = await client.fetch_channel('850364625479532545')
embed = discord.Embed(title="Ticket Created",
description="",
color=discord.Colour.green())
embed.add_field(name=f'**By:** {ctx.author}',value= f'**ID:** {ctx.author.id}')
await logchannel.send(embed=embed)
#--- Ticket Close ---
#client.command()
#commands.guild_only()
async def close(ctx):
print(f'{ctx.author} | {ctx.author.id} -> {client.command_prefix}close')
if ctx.channel.type != discord.ChannelType.private:
admin_roles = [834126146215477348,835608325273157733,838859643224326144,835582821221138472,835914273402126376]
if ctx.channel.name == f'ticket-{ctx.author.id}':
await ctx.channel.delete()
elif admin_roles and 'ticket' in ctx.channel.name or ctx.author.id in administrator_ids and 'ticket' in ctx.channel.name:
await ctx.channel.delete()
else:
await ctx.message.delete()
logchannel = await client.fetch_channel('850364625479532545')
embed = discord.Embed(title="Ticket Closed",
description="",
color=discord.Colour.red())
embed.add_field(name=f'**By:** {ctx.author}',value= f'**ID:** {ctx.author.id}')
await logchannel.send(embed=embed)
Tip: if you want to create a public bot don't use handwritten channel id, you'd better save to file for all servers in json file and set it with command.
For example this:
{
"server identifier": "system channel identifier",
...
}
I don't know what's wrong with the code.
I'm trying to make a poll command in Discord.py but want at the end the bot to send a list of users that reacted with 1️⃣ and another list of people that reacted with 2️⃣.
This is my code so far:
async def poll(ctx, q1, q2, time : int):
await ctx.send(f"React with 1 to vote for **{q1}** and with 2 to vote for **{q2}**\n**Poll Lasts for {time} seconds**")
poll = discord.Embed(title = "Poll", color = discord.Color.blue())
poll.add_field(name = f"{q1} 1️⃣", value = "")
poll.add_field(name = f"{q2} 2️⃣", value = "")
msg = await ctx.send(embed = poll)
r1 = await msg.add_reaction("1️⃣")
r2 = await msg.add_reaction("2️⃣")
await asyncio.sleep(time)
await ctx.send("Times up! **Poll Closed**")
new_msg = discord.utils.get(client.cached_messages,id = msg.id)
users1 = await r1.reactions[0].users().flatten()
users1.pop(users1.index(client.user))
users2 = await r2.reactions[0].users().flatten()
users2.pop(users2.index(client.user))
em=discord.Embed(title=f'Votes for {q1}', description=" , ".join(user.name for user in users1),color = discord.Colour.blue())
await ctx.send(embed = em)
em=discord.Embed(title=f'Votes for {q2}', description=" , ".join(user.name for user in users2),color = discord.Colour.blue())
await ctx.send(embed = em)
And this is the error I am getting:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'reactions'
Message.add_reaction returns None, you can't use these two lines
r1 = await msg.add_reaction("1️⃣")
r2 = await msg.add_reaction("2️⃣")
Easiest approach would be to fetch the message again with the updated reactions
message = await ctx.send("Whatever")
await message.add_reaction("1️⃣")
await message.add_reaction("2️⃣")
await asyncio.sleep(10)
updated_message = await ctx.channel.fetch_message(message.id)
users1, users2 = [], []
for r in updated_message.reactions:
print(f"{str(r)} was added {r.count} times")
if str(r) == "1️⃣":
users = await r.users().flatten()
users1.extend(users)
elif str(r) == "2️⃣":
users = await r.users().flatten()
users2.extend(users)
# `users1` and `users2` are lists of users that reacted with `1️⃣` and `2️⃣` accordingly
Reference:
Messageable.fetch_message
Message.reactions
Reaction.count
Reaction.users
I was making a discord bot in Python, and when i wanted to run it - the error occurred - expected an indented block, I'll show some code :
I tried to move some things but it didn't work. Also I'm completely new to Python and I have done some things with the tutorials on YouTube. Help me please.
import discord
import random
client = discord.Client()
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.idle, activity=discord.Game('?help'))
print('Bot jest online.')
#client.event
async def on_message(message):
id = client.get_guild(586513031765426198)
if message.content.find("?ping") != -1:
await message.channel.send("Pong! Jestem gotowy do użytku!")
if message.content.find("?plany") != -1:
await message.channel.send("Mam zamiar dodać do bota dużo komend!")
if message.content == "?rzut-monetą":
variable = [
'Orzeł!',
'Reszka!',]
await message.channel.send(random.choice(variable))
if message.content == "?pomoc":
embed = discord.Embed(title="Komendy!", description="Znajdziecie tutaj wszystkie komendy.", colour=discord.Colour.red())
embed.add_field(name="!ping", value="Sprawdza, czy bot jest teraz online.", inline=False)
embed.add_field(name="!info", value="Daje informacje o bocie.", inline=False)
embed.add_field(name="!plany", value="Pokazuje plany na przyszłość dotyczące bota.", inline=False)
embed.add_field(name="!pomoc", value="Pokazuje tą wiadomość.", inline=False)
embed.add_field(name="!rzut-monetą", value="Losuje pomiędzy orłem a reszką. Świetne do rozstrzygania sporów.", inline=False)
await message.channel.send(content=None, embed=embed)
if message.content == "?info":
embed = discord.Embed(title="Informacje!", description="Krótkie info o bocie.", colour=discord.Colour.blue())
embed.add_field(name="Autor", value="Pomi ;3#2203", inline=False)
embed.add_field(name="O bocie", value="Zadanie tego bota to głównie rozrywka, ale ma też wbudowanego auto-moderatora do polskich przekleństw.", inline=False)
await message.channel.send(content=None, embed=embed)
one line under the ?info command the first embed is showing on a red background. What could this mean?
You're missing an indented block on the last if
Where you have:
...
if message.content == "?info":
embed = discord.Embed(title="Informacje!", description="Krótkie info o bocie.", colour=discord.Colour.blue())
embed.add_field(name="Autor", value="Pomi ;3#2203", inline=False)
embed.add_field(name="O bocie", value="Zadanie tego bota to głównie rozrywka, ale ma też wbudowanego auto-moderatora do polskich przekleństw.", inline=False)
await message.channel.send(content=None, embed=embed)
Replace with:
...
if message.content == "?info":
embed = discord.Embed(title="Informacje!", description="Krótkie info o bocie.", colour=discord.Colour.blue())
embed.add_field(name="Autor", value="Pomi ;3#2203", inline=False)
embed.add_field(name="O bocie", value="Zadanie tego bota to głównie rozrywka, ale ma też wbudowanego auto-moderatora do polskich przekleństw.", inline=False)
await message.channel.send(content=None, embed=embed)
Note. If you intended to execute only part of that block, unindent whatever you don't care about the condition.