I'm trying to make a help that relies on reactions, I got this code
import discord
from discord import Embed
from discord.ext import commands
class Helptest(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def helpreee(self, ctx):
await ctx.message.delete()
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.message.delete()
await msg.reaction.clear()
msg1 = await msg.edit("Hewwo")
await msg1.add_reaction("⬅️")
reaction, user = await client.wait_for('reaction_add', timeout=5, check=check)
if reaction.emoji == '⬅️':
await msg.edit("Eh idk just react")
return
elif reaction.emoji == '⬅️':
await ctx.send("AAA")
except asyncio.TimeoutError:
await ctx.send("Timed out")
#helpreee.error
async def helpreee_error(self, ctx, error):
await ctx.send(error)
print(error)
raise error
def setup(client):
client.add_cog(Helptest(client))
but it didn't work, I get an error.
The error is:
Traceback (most recent call last): File
"C:\Users\PC\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py",
line 607, in _load_from_module_spec
spec.loader.exec_module(lib) File "", line 779, in exec_module File
"", line 916, in get_code File
"", line 846, in source_to_code
File "", line 219, in
_call_with_frames_removed File "C:\Users\PC\Desktop\Code\Waifu Bot\cogs\testhelp.py", line 22
try:
^ IndentationError: unindent does not match any outer indentation level
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File
"C:\Users\PC\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py",
line 312, in _run_event
await coro(*args, **kwargs) File "C:\Users\PC\Desktop\Code\Waifu Bot\setup.py", line 95, in on_ready
raise e File "C:\Users\PC\Desktop\Code\Waifu Bot\setup.py", line 92, in on_ready
client.load_extension(cog) File "C:\Users\PC\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py",
line 664, in load_extension
self._load_from_module_spec(spec, name) File "C:\Users\PC\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py",
line 610, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.testhelp'
raised an error: IndentationError: unindent does not match any outer
indentation level (testhelp.py, line 22)
This is just a simple indentation error (at try...except):
import discord
from discord import Embed
from discord.ext import commands
class Helptest(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def helpreee(self, ctx):
await ctx.message.delete()
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.message.delete()
await msg.reaction.clear()
msg1 = await msg.edit("Hewwo")
await msg1.add_reaction("⬅️")
reaction, user = await client.wait_for('reaction_add', timeout=5, check=check)
if reaction.emoji == '⬅️':
await msg.edit("Eh idk just react")
return
elif reaction.emoji == '⬅️':
await ctx.send("AAA")
except asyncio.TimeoutError: #Indent error here, delete one tabulation
await ctx.send("Timed out") #Also Delete one tabulation here
#helpreee.error
async def helpreee_error(self, ctx, error):
await ctx.send(error)
print(error)
raise error
def setup(client):
client.add_cog(Helptest(client))
PS: To avoid indent error, avoid to skip a line after a code line, it will be easier to detect those errors and your code will be more understandable ^^
Related
I'm trying to make a blackjack command for my Discord Bot in python, I'm making small codes and little by little testing and improving, see below:
import discord
from discord.ext import commands
from discord import app_commands
import random, json, datetime
class bj(discord.ui.Button):
def __init__(self, game ,gamesum, player_cards):
super().__init__()
self.value = None
#discord.ui.button (label="Hit", style=discord.ButtonStyle.blurple)
async def confirm(self, button: discord.ui.Button, interaction: discord. Interaction):
self.value = True
self.stop()
value_1=["A", 1,2,3,4,5,6,7,8,9,10,"J","Q","K",]
nype_1=["♦️","♠️","♥️","♣️"]
card_value_3 = random.randint(0, len(value_1) - 1)
nype_card_3 = random.randint(0, len(nype_1) - 1)
card_3 = f"{card_value_3[card_value_3]} {card_value_3[nype_card_3]}"
await match.edit()
match.edit_field(name='Your hand', value=f"{player_cards} {card_value_3}{nype_card_3}")
if type(card_value_3)==str:
if value_card_3=="A":
value_letter_3=11
else:
value_letter_3=10
else:
value_letter_3=value_card_3
class client(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
async def setup_hook(self) -> None:
self.add_view(DropdownView())
async def on_ready(self):
await aclient.change_presence(activity = discord.Streaming(name = "/news", url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"))
await self.wait_until_ready()
if not self.synced:
await tree.sync()
self.synced = True
print(f"We entered as {self.user}!")
print(f"That has the ID {self.user.id}")
client = client()
tree = app_commands.CommandTree(aclient)
#tree.command(name='blackjack', description='Play a game of blackjack')
async def blackjack(interaction: discord.Interaction, amount:int):
await open_account(interaction.user)
money = await add_money(interaction.user)
if amount>money[0]:
await interaction.response.send_message(f"You don't have all this amount {interaction.user.mention}.")
else:
if quantity<0:
await interaction.response.send_message(f"You must enter a positive value")
else:
value_1=["A",2,3,4,5,6,7,8,9,10,'J','Q',"K"]
nype_1=["♦️","♠️","♥️","♣️"]
value_card_a = random.randint(0, len(value_1) - 1)
nype_card_a = random.randint(0, len(nype_1) - 1)
letter_a = f"{value_1[value_card_a]}{nype_1[nype_letter_a]}"
b_card_value = random.randint(0, len(1_value) - 1)
nype_card_b = random.randint(0, len(nype_1) - 1)
letter_b = f"{value_1[value_card_b]}{nype_1[nype_letter_a]}"
player_cards = f"{card_a} {card_b}"
if type(value_card_a)==str:
if value_card_a=="A":
value_letter_a=11
else:
value_letter_a=10
else:
value_card_a=value_card_a
if type(value_card_b)==str:
if value_card_b=="A":
value_letter_b=11
else:
value_letter_b=10
else:
value_card_b=value_card_b
sum_of_game=value_card_a+value_card_b
await add_money(interaction.user, -1*amount)
if sum_of_game==21:
result='Blackjack'
titulo_resultado=f'You won ~~K~~ {1.5*amount}'
else:
result=sum_of_game
titulo_resultado=f'You invested ~~K~~ {amount} in this blackjack'
departure=discord.Embed(
description=f'{result_title}',
colour=discord.Color.random()
)
match.add_field(name='Your hand', value=f"{player_cards}\n{result}")
if result=='Blackjack':
await add_money(interaction.user, 1.5*amount)
await interaction.response.send_message(embed=game, view=bj(game ,gamesum, player_cards))
async def open_account(user):
users = await bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]['wallet'] = 0
users[str(user.id)]['bank']= 0
with open("money.json", "w") as f:
json.dump(users, f)
return true
async def bank_data():
with open("money.json", "r") as f:
users = json.load(f)
return users
async def add_money(user, change=0, mode = "wallet"):
users = await bank_data()
users[str(user.id)][mode] +=change
with open("money.json", "w") as f:
json.dump(users, f)
money = [users[str(user.id)]["wallet"], users[str(user.id)]["bank"]]
return money
aclient.run(Token)
But in await interaction.response.send_message(embed=match, view=bj(match ,game_sum, player_cards)) is reporting the error
2023-02-06 19:14:31 ERROR discord.app_commands.tree Ignoring exception in command 'blackjack'
Traceback (most recent call last):
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 1155, in blackjack
await interaction.response.send_message(embed=partida, view=bj(partida ,soma_de_jogo, cartas_jogador))
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/interactions.py", line 754, in send_message
params = interaction_message_response_params(
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/webhook/async_.py", line 577, in interaction_message_response_params
data['components'] = view.to_components()
AttributeError: 'bj' object has no attribute 'to_components'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'blackjack' raised an exception: AttributeError: 'bj' object has no attribute 'to_components'
I tried to interpret the error, as I recently started programming, it didn't help much, I asked in ChatGPT, and it also didn't help much (the error didn't even change), so the artificial intelligence itself suggested that I come and ask here, I hope it helps me help(Oh, and sorry for not leaving everything organized and well separated, they said there was a lot of code and little information).
I just switched to Discord.py v2 after switching using nextcord for 1 or 2 months.
Im having a issue where no commands work
like no commands at all
i changed everything from "nextcord" to "discord" and even changed the setups in the cogs to the new async versions
events work, but commands themselves dont
i tried everything i knew but still didnt fix it
i tried looking in the discord doc but still couldnt find a soloution
my current code:
import discord
from discord.ext import commands
from discord.ext.commands.core import has_permissions
import asyncio
import os
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='+', intents=intents)
##COGS
#bot.event
async def on_ready():
await asyncio.sleep(1)
print(f'We have logged in as {bot.user}')
await bot.change_presence(activity=discord.Game(name="in the Mountains"))
#bot.command()
#has_permissions(administrator = True)
async def load(ctx, arg, extension):
if ctx.author.id == 498839148904579092:
bot.load_extension(f"{arg}.{extension}")
embed = discord.Embed(description=f"{extension} module loaded!", colour=discord.Colour.dark_green())
await ctx.send(embed = embed)
print(f"{extension} loaded")
#bot.command()
#has_permissions(administrator = True)
async def unload(ctx, arg, extension):
if ctx.author.id == 498839148904579092:
bot.unload_extension(f"{arg}.{extension}")
embed = discord.Embed(description=f"{extension} module unloaded!", colour=discord.Colour.dark_green())
await ctx.send(embed = embed)
print(f"{extension} unloaded")
#bot.command()
#has_permissions(administrator = True)
async def reload(ctx, arg, extension):
if ctx.author.id == 498839148904579092:
bot.reload_extension(f"{arg}.{extension}")
embed = discord.Embed(description=f"{extension} module reloaded!", colour=discord.Colour.dark_green())
await ctx.send(embed = embed)
print(f"{extension} reloaded")
#load.error
async def alreadyloaded(ctx, error):
if isinstance(error, commands.CommandInvokeError):
embed = discord.Embed(colour=discord.Colour.dark_red())
embed.set_author(icon_url="https://cdn.discordapp.com/attachments/883349890921545748/927946906271887430/W0019f8UlvqD3dDC5.png", name="Command Invoke Error! [LOAD]")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/883349890921545748/927946906271887430/W0019f8UlvqD3dDC5.png")
embed.add_field(name="commands.CommandInvokeError", value=error, inline=True)
embed.add_field(name="Maybe...", value="The Extension is Non-Exsistant or cannot be Loaded", inline=True)
embed.set_footer(text="get a list of Modules with [+modules]!")
await ctx.send(embed = embed, delete_after = 10)
elif isinstance(error, commands.MissingPermissions):
await ctx.message.delete()
await ctx.send(f"{ctx.author.mention}, that Command is Admin only!", delete_after = 3)
return
#unload.error
async def alreadyunloaded(ctx, error):
if isinstance(error, commands.CommandInvokeError):
embed = discord.Embed(colour=discord.Colour.dark_red())
embed.set_author(icon_url="https://cdn.discordapp.com/attachments/883349890921545748/927946906271887430/W0019f8UlvqD3dDC5.png", name="Command Invoke Error! [UNLOAD]")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/883349890921545748/927946906271887430/W0019f8UlvqD3dDC5.png")
embed.add_field(name="commands.CommandInvokeError", value=error, inline=True)
embed.add_field(name="Maybe...", value="The Extension is Non-Exsistant or cannot be Unloaded", inline=True)
embed.set_footer(text="get a list of Modules with [+modules]!")
await ctx.send(embed = embed, delete_after = 10)
return
elif isinstance(error, commands.MissingPermissions):
await ctx.message.delete()
await ctx.send(f"{ctx.author.mention}, that Command is Admin only!", delete_after = 3)
return
#bot.command()
async def online(ctx):
print("1")
await ctx.channel.send("online")
print("hello")
async def main():
async with bot:
#await load_extensions()
await bot.start("bot auth code")
asyncio.run(main())
Discord.py v2.0 has migrated to api v10, and with this has come the introduction of Intents.message_content, which is disabled by default.
This means that you will need to explicitly enable it in code and in the panel, at https://discord.com/developers/applications.
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='+', intents=intents)
I found a command that sends the latest deleted message. While testing I found that when I delete a message it sends a traceback error to the console. Here's the traceback error and code.
Ignoring exception in on_message_delete
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Isla/cogs/awp.py", line 21, in on_message_delete
if msg.author.client:
AttributeError: 'Member' object has no attribute 'client'
import discord
from discord.ext import commands
import datetime
import editdistance
import re
invitere = r"(?:https?:\/\/)?discord(?:\.gg|app\.com\/invite)?\/(?:#\/)([a-zA-Z0-9-]*)"
invitere2 = r"(http[s]?:\/\/)*discord((app\.com\/invite)|(\.gg))\/(invite\/)?(#\/)?([A-Za-z0-9\-]+)(\/)?"
class Awp(commands.Cog):
def __init__(self, client):
self.client = client
self.snipes = {}
#client.listen('on_message_delete')
async def on_message_delete(msg):
if msg.author.client:
return
self.snipes[msg.channel.id] = msg
#client.listen('on_message_edit')
async def on_message_edit(before, after):
if before.author.client or after.author.client:
return # DEPARTMENT OF REDUNDANCY DEPARTMENT
if (editdistance.eval(before.content, after.content) >= 10) and (
len(before.content) > len(after.content)):
self.snipes[before.channel.id] = [before, after]
#commands.Cog.listener()
async def on_ready(self):
print('Gifs bot is online.')
def sanitise(self, string):
if len(string) > 1024:
string = string[0:1021] + "..."
string = re.sub(invitere2, '[INVITE REDACTED]', string)
return string
#commands.command()
async def awp(self, ctx):
'"Snipes" someone\'s message that\'s been edited or deleted.'
try:
snipe = self.snipes[ctx.channel.id]
except KeyError:
return await ctx.send('No snipes in this channel!')
if snipe is None:
return await ctx.send('No snipes in this channel!')
# there's gonna be a snipe after this point
emb = discord.Embed()
if type(snipe) == list: # edit snipe
emb.set_author(
name=str(snipe[0].author),
icon_url=snipe[0].author.avatar_url)
emb.colour = snipe[0].author.colour
emb.add_field(
name='Before',
value=self.sanitise(snipe[0].content),
inline=False)
emb.add_field(
name='After',
value=self.sanitise(snipe[1].content),
inline=False)
emb.timestamp = snipe[0].created_at
else: # delete snipe
emb.set_author(
name=str(snipe.author),
icon_url=snipe.author.avatar_url)
emb.description = self.sanitise(snipe.content)
emb.colour = snipe.author.colour
emb.timestamp = snipe.created_at
emb.set_footer(
text=f'Message sniped by {str(ctx.author)}',
icon_url=ctx.author.avatar_url)
await ctx.send(embed=emb)
self.snipes[ctx.channel.id] = None
def setup(client):
client.add_cog(Awp(client))
You simply have to change message.author.client to message.author.bot, regardless of you using client or bot.
References:
discord.Member
Im having this issue and i still cant find a solution this is the code
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
if payload.message_id == commands.reaction_message.id and commands.reaction_role != None:
await payload.member.add_roles(commands.reaction_role)
#commands.Cog.listener()
async def on_raw_reaction_remove(self, payload):
if payload.message_id == commands.reaction_message.id and commands.reaction_role != None:
guild = self.client.get_guild(payload.guild_id)
member = guild.get_member(payload.user_id)
await member.remove_roles(commands.reaction_role)
#commands.command()
async def set_reaction_message(self, ctx, message_id=None, role_id=None):
for channel in ctx.guild.channels:
try:
commands.reaction_message = await channel.fetch_message(int(message_id))
break
except:
pass
problem: File "c:\Users\MY-NAME\Desktop\Overige en school\Discord Bot\cogs\reaction.py", line 17, in on_raw_reaction_add
await payload.member.add_roles(commands.reaction_role)
AttributeError: 'RawReactionActionEvent' object has no attribute 'member'
can someone please help me this is been bothering me now for 2days and i can't even find a solution
I know according to the documentation discord.RawReactionActionEvent payload has the object member. But why don't you make it easier for yourself and get the member in the same way as in your on_raw_reaction_remove event? The following should work.
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
if payload.message_id == commands.reaction_message.id and commands.reaction_role != None:
guild = self.client.get_guild(payload.guild_id)
member = guild.get_member(payload.user_id)
await member.add_roles(commands.reaction_role)
#commands.Cog.listener()
async def on_raw_reaction_remove(self, payload):
if payload.message_id == commands.reaction_message.id and commands.reaction_role != None:
guild = self.client.get_guild(payload.guild_id)
member = guild.get_member(payload.user_id)
await member.remove_roles(commands.reaction_role)
#commands.command()
async def set_reaction_message(self, ctx, message_id=None, role_id=None):
for channel in ctx.guild.channels:
try:
commands.reaction_message = await channel.fetch_message(int(message_id))
break
except:
pass
I'm setting up a discord bot, and I want to have the bot send a confirmation or error message after the commands "ban" and "kick", can anyone help?
I have tried creating another separate command with the same arguments, except just having it send the expected message.
#client.event
async def on_ready():
print('Bot is ready!')
#client.event
async def on_member_join(ctx, member):
print(f'{member} has joined {ctx.guild.name}.')
#client.event
async def on_member_remove(ctx, member):
print(f'{member} has left {ctx.guild.name}.')
#client.event
async def on_member_join(member):
role = discord.utils.get(member.server.roles, name="Member")
await client.add_roles(member, role)
#client.command()
async def ping(ctx):
await ctx.send(f'Pong! :ping_pong: **{round(client.latency * 1000)}ms** ')
#client.command()
async def purge(ctx, amount):
await ctx.channel.purge(limit=amount)
await ctx.send(f'{member.display_name} has been kicked.')
#client.command()
async def kick(ctx, member : discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f'{member.display_name} has been kicked.'')
#client.command()
async def ban(ctx, member : discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f'The Ban Hammer has Spoken! {member.display_name} has been banned!')
#client.command()
async def pardon(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.banned_users
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'Unbanned {member.display_name}')
In actuality, I think it would be great, because they clash with each other and probably will send a message, but it went wrong.
At the end of the kick command delete that last '. And also do {member.name} or {member}