#discord-bots
1 messages · Page 673 of 1
Weirddd
thx
help?
hm
why are u sending the message inside for 😭
one second let me see if this exists
how do I get a unicode of a custom emoji
you don't
custom emoji's dont have a unicode value
it's name:emojiId, not unicode
yeah what infernum said
@bot.command()
async def test(ctx):
message = await ctx.send('test')
emoji = 'rick_roll:'
await message.add_reaction(emoji)
await ctx.add_reaction(emoji)
error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 10014): Unknown Emoji
what did I say....
.
!d discord.ext.commands.Bot.get_emoji
get_emoji(id, /)```
Returns an emoji with the given ID.
<:name:id>
or <name🆔>
the one I said should work as long as the bot is in the server of the emoji
ohh actually it isnt i am trying to use custom emoji
hmmm but bots are possible to emojis from other server with correct provided id?
I'm not sure I understood that correctly
guys i use the discord_slash module to make slash commands but whenever i tried to run my bot i got this error
om_type
if issubclass(t, discord.abc.User): return cls.USER
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/abc.py", line 102, in __subclasscheck__
return _abc_subclasscheck(cls, subclass)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/typing.py", line 1108, in _proto_hook
raise TypeError("Protocols with non-method members"
TypeError: Protocols with non-method members don't support issubclass()
here is my code
@slash.slash(name = 'eliminate', description = 'Eliminate someone from a simon says game')
async def eliminate(ctx: SlashContext, member: discord.Member):
guild = member.guild
if ctx.channel.id == 919563757204693103:
if guild.get_role(919571300467474543) in ctx.author.roles:
if guild.get_role(919570782185750578) in member.roles:
await member.remove_roles(919570782185750578)
await ctx.send("{0} was eliminated! R.I.P".format(member.name))
else:
await ctx.message.delete()
can you show the full traceback?
How do I play an mp3 with my bot?
sure
audio_source = discord.FFmpegPCMAudio(executable="path/to/name.exe", source="path/to/name.mp3")
!d discord.VoiceClient.play
play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/master/api.html#discord.AudioSource "discord.AudioSource").
The finalizer, `after` is called after the source has been exhausted or an error occurred.
If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be displayed as if it were raised.
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
@visual island I dont think thats what I was looking for, im just getting this error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: test.mp3 was not found.
and its from this line audio_source = discord.FFmpegPCMAudio(executable="test.exe", source="test.mp3")
i have seen bots using emojis from other servers
e.g. dank memer
yes because the emojis they use are in a server where the bot is aswell
ohh
thank you
Np
someone help pleas
if i have subclassed my bot, can i still do @bot.event?
yes, as long as you have the instance
alr
but is it recommended? cuz i see some other bots doing everything just in the class
yes as in?
oh okay thanks
also just curious why some bots do py if __name__ == "__main__"": bot = MyBot() bot.run
and what it means
Yeah you can, but if you have an on_message event, make sure that you are processing the message by calling the process_commands method
plz some1 help
i have an on_message listener in a cog
Normally when I subclass, I don't override the default on_message event, rather I just use event listeners
does it affect?
Bot.listen()
alr then
So it will not affect
so i can have checks normally?
checks?
@bot.check
Hm yeah you can
kden thbanks
nobody :c
Well what version of discord.py are you using?
crap i use 2.0
wait do you actually use discord_slash
I don't
oh
I use disnake
ok so i converted it back to a normal command (instead of slash) and i got this traceback
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "/home/container/bot.py", line 227, in eliminate
await member.remove_roles(919570782185750578)
File "/home/container/.local/lib/python3.10/site-packages/discord/member.py", line 891, in remove_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'int' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'id'
the remove_roles takes a discord.Role not an int
if it doesn't take an int, it prob doesn't take a str 💀
no.
it takes a discord.Role
you can do role = guild.get_role(role_id)
oh
and pass role
ok but you can still use guild.get_role in if statements?
yes
oh alright
can someone help me with a slash command issue?
Sure
@maiden fable here's the issue, you see how it shows up in my list as hello
it's name was changed in my code like 8 hours ago to results
why won't it update?
Discord/Lib Issue
is there a fix?
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
extension = filename[:-3]
try:
self.load_extension(f'cogs.{extension}')
print(f"Successfully loaded extension \'{extension}\'")
except Exception as e:
exception = f"{type(e).__name__}: \'{e}\'"
print(f"---------------------\nFailed to load extension \'{extension}\'\n-- {exception}")
```i've tried bringing this into the subclassed bot (`class MyBot(commands.Bot):`) and changed `bot.` to `self.` but it's now telling me self is not defined
Nope iirc
damn that sucks
class MyBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix='.')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
extension = filename[:-3]
try:
self.load_extension(f'cogs.{extension}')
print(f"Successfully loaded extension \'{extension}\'")
except Exception as e:
exception = f"{type(e).__name__}: \'{e}\'"
print(f"---------------------\nFailed to load extension \'{extension}\'\n-- {exception}")
Kayle, do you know a fix to my issue by any chance?
move it inside on ready or another function, then call the function somewhere
oh
no idea, either you did something wrong in code or it's discord freaking out and being slow to updating that
hmm
userinfo/guildinfo
already did that
ok, im gonna give it another day to try to fix itself
or a whatis command and how it works is you pass in a guild/user/channel/role id and it'll give info
I recommend disnake though, you can instantly see updated slash commands using a test_guilds kwarg (works in other forks too I think, but the name isn't test-guilds)
ok, ill try that
eh, I could but it looks kinda useless 🤔
how do i start an async thread when someone clicks a button, I'm trying to make something that handles multiple interactions with different people at once
would loading extensions in on_ready be a good idea (subclassed bot)
on_ready gets called multiple times so no (you can still do it though). You can create another function and load the cogs there.
@boreal ravine @maiden fable I found a fix, i needed to add sync_commands and sync_on_cog_reload
o nice
alr then
so like
?
class MyBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix='.')
def loadcogs(self):
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
extension = filename[:-3]
try:
self.load_extension(f'cogs.{extension}')
print(f"Successfully loaded extension \'{extension}\'")
except Exception as e:
exception = f"{type(e).__name__}: \'{e}\'"
print(f"---------------------\nFailed to load extension \'{extension}\'\n-- {exception}")
mhm
here's another error though @boreal ravine When i try to get a response from my slash command, i get an error with the button
why do you per se want to extend your bot class to load cogs? no need
how can i make a command loop ? like i do a command with embed and after 10 seconds it deletes itself and then it runs again
¯_(ツ)_/¯
here's the code
It happens when you use 3rd party libs
concrete?
can you copy and paste it here cuz i cant read it
mhm discord components
sure
error too
sure
let me do that, give me one sec...
Here's the code:
@slash.slash(name="results", description="Brings up survey results. Must be `administrator` to run this command")
async def results(ctx: SlashContext):#disnake
print("")
print(f"Results command triggered {time.strftime('%H:%M:%S, %m-%d-%Y')}...")
if ctx.author.guild_permissions.administrator:
embed = discord.Embed(color = 0x800020)
embed.title = "Survey Results:"
embed.description = "Hello `Administrator`, please click on the button below to access the survey results!!"
embed.timestamp=datetime.datetime.utcnow()
embed.set_footer(text=f'AHSweather v{_version_} \u200b')
#bcc = client.get_channel(886307415518240768)#general
b1 = Button(style=ButtonStyle.URL, label = 'Go to the survey results!', url="https://www.surveyhero.com/user/surveys/657976/responses")
#b2 = Button(style=ButtonStyle.grey, label = "I'm neutral")
#b3 = Button(style=ButtonStyle.red, label = 'I did not like it')
await ctx.send(embed=embed, components=[b1], hidden=True)
else:
await ctx.send(f"Sorry, you don't have the permissions to run this command! You are missing the following permissions: `administrator`", hidden=True)
An exception has occurred while executing command `results`:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\client.py", line 1352, in invoke_command
await func.invoke(ctx, **args)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\model.py", line 210, in invoke
return await self.func(*args, **kwargs)
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python310/AHSweather_bot_3.4.10.py", line 855, in results
await ctx.send(embed=embed, components=[b1], hidden=True)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\context.py", line 215, in send
if components and not all(comp.get("type") == 1 for comp in components):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\context.py", line 215, in <genexpr>
if components and not all(comp.get("type") == 1 for comp in components):
AttributeError: 'Button' object has no attribute 'get'
use that and not components
sending command that purges itself after 10 seconds and then like i sent it again but actually it was the command that sent itself
.send has a delete_after kwarg
'Button' object has no attribute 'get'
Which module are you using?
oops
discord_slash
guys gimme command ideas
3rd party libs tends to have those types of errors, you can make an issue on the github and hope that the developer fixes it or you could use a fork (im saying this cause I don't know why that error raises)
im not the one using discord_slash ;-;
kick, ban, mute - those are the only basic commands i can think of
even they might be too dificult for you
akinator?
connect4?
tictactoe?
suggestion system?
levelling system?
already made all of them except mute since my bot isn't gonna be a moderation bot
hangman?
too difficult for him
never
- akinator in discord sounds cool but at the same time no
- sure
- sure
- useless
- i guess
hangman?
yes
see not that difficult for him
my friend has a lib for those types of games, https://github.com/andrewthederp/Disgames/ <= check it out here
even i have those in my bot
- There are a million bots having those
kayle do you have a bot
obviously, i wouldnt be in here if i didnt have one
there are a million chatbots too
yes
is it open source
it's on github but it's private
But most of them don't remember your name (:
you store that kind of information?
:O i know andrew
Yups, in a JSON File... The users know about that anyways 🤷♂️
can i test your bot?
my bot isnt public, its only in my server right now
can I join your server
yeah i wanna join
i mean sure
😶
dm the invite :D
what invite 👀
Private Server Invite
bot server?
Mhm
I want to yeet features to my bot, gib invite if you can
how can i make command do another command ?
oh now I remember what I had to do, fix my bot's constant files ...
!d discord.ext.commands.Context.invoke
await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls a command with the arguments given.
This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.
Note
This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.
You must take care in passing the proper arguments when using this function.
I'm waiting the time when this embed gets paginated, but I broke my constants and the bot cant even run atm 🤦
it's a bit too long
Hmmmmmmm
Just use views
Tbh I love the implementation of ui.View
Not talking about Internals, but the end developer implementation
trying to make a giveaway function
@bot.command()
async def test(ctx, time=None, *, prize=None):
if time == None:
return await ctx.send('time bata ')
elif prize == None:
return await ctx.send('abe prize kya hai?')
embed = discord.Embed(title='hm', description=f'{prize}', color=0xcf244)
embed.set_footer(text=f'ends in {time}')
time_covert = {"s":1, "m":60, 'h':3600, 'd':86400}
gaw_time = int(time[0]) * time_covert[time[-1]]
gaw_msg = await ctx.send(embed=embed)
await gaw_msg.add_reaction('🎉')
await asyncio.sleep(gaw_time)
gaw_msg2 = await ctx.channel.fetch_message(gaw_msg.id)
users = await gaw_msg2.add_reaction[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
await ctx.send(f'{winner.mention} and won {prize}')```
error:
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'method' object is not subscriptable
i used invoke on my command and after some time it did this Command raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message does anyone know why ?
is there any API to make discord bot search google?
U need to use a module
what module?
!pypi google
This, iirc
ok, thanks :3
it then marked purge command and invoke command as something was wrong and i dont know why
you tried to delete the authors message?
can it be used in replit? (import google)
Idk, seems like it
ok, thanks
replit bad
this is how you assigned a help command to bot, right? ```py
bot.help_command = MyNewHelp()
what I guess is after interaction it has 1 task to do and when it's done it wont repeat it
Just set the help_command kwarg when initializing the bot
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
This kwarg
but the other one works as well, right?
Yes
i tried fixing the buttons with looping but it makes sounds and its just not working, any other ideas ?
hm
does discord.py 2.0 use "on_raw_reaction_add" or "on_reaction_add"
@manic wing nice bot btw, 7.5/10 rating
both still exists
any difference?
on_raw works with shit that’s not in cache
well my bot host uses caching and stuff so i will just use on_reaction_add
pog
pog
not pog since idk how to use reactions in an on_message event 💀
Use reactions in which way
what is this
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Also you can’t have empty field values like that
ye ik, just what make it appear
wait really?
I mean you can if you use unicode chars
But if you have an empty string that won’t work.
so basically i have this really weird and imagined code:
msg = await ctx.send("tezt")
await msg.reaction.add("💀")
ok but how else am i gonna specify reaction if i get an error and there's no obj 💀
Use logic to check stuff first
And I thought you said this was in a on_message
There’s no ctx in on_message
!d discord.Message.add_reaction || await msg.add_reaction(...) and if its on_message it would be message.channel.send(...)
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
breh already enter value, and reindent all the code, why still appear
Send the code
wait, i reload it
Hello everyone. I am trying to make a welcome message when someone joins my server, but for some reason it doesn't work. Anyone got any ideas?
done
send code
@client.event
async def on_member_join(member):
await client.get_channel(idchannel).send(f"{member.name} has joined")```
here
It still doesn't work for some reason
(if u determine client as bot change it to bot, also change the idchannel by the ID of channel u want to be the channel to welcome
well i did change it and it still doesn't work :/
send ur code
dms?
k
has anybody found a way to fix it ?
I'm trying to paginate a help embed smh
I alrd took a look at pinned messages
so...?
Would have made sense
from my last experience (idk the others) the button no longer work... since InteractionType removed in discord.py
what?
seems to work but once
wait, in u can work? how :l
bhre no one knows why my error appear? and how to remove it
strange request but can someone turn this into a png
I'm new to making discord bots and i need some help with a problem im having dm me if you think you can help
what problem
burh .gif can't be changed to .png
can i dm you about it?
ok
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'open_account' is not defined
import discord
from discord.ext import commands
import json
class Economy(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def get_bank_data():
with open("bank.json", 'r') as f:
users = json.load(f)
return users
async def open_account(user):
users = await get_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("bank.json", "w") as f:
json.dump(users, f)
return True
@commands.command()
async def balance(self, ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
wallet_amt = users[str(user.id)]["Wallet"]
bank_amt = users[str(user.id)]["Bank"]
em = discord.Embed(title=f"{ctx.author.name}'s Balance", color= discord.Color.teal)
em.add_field(name="Wallet", value=wallet_amt)
em.add_field(name="Bank", value=bank_amt)
await ctx.send(embed=em)
def setup(bot):
bot.add_cog(Economy(bot))
my economy cog

how can i add role to someone when someone presses a button ?
im using discord_components
you miss the command() decorator on open_account
oo some code i can "take inspiration" from
btw seems like just a helper function to me
but the open account thing isnt a command its a function for defining open_account
yea just saw that , py users = await get_bank_data() here , this should be py users = await self.get_bank_data()
and include self as the first arg in those functions
( swas.py , but in cogs)
thats what im doing im making his code in cog version for the beginners
anyways
open_account will still not be defined
self.open_account.............
how can I shorten this code to one line ```py
m = ctx.guild.get_member(645582953434316802)
await m.send('hi')
i dont define it like that
you are in a class
await ctx.send(embed=embed, components=[
[Button(style=ButtonStyle.URL, label="Refresh")]]
as i am using await
" await open_account(ctx.author)"
add )at the end
do i still use self?
ofcourse
await ctx.send(embed=embed, components=[
[Button(style=ButtonStyle.URL, label="Refresh")]])
C:\Users\ADMIN\PycharmProjects\Fluxo>python main.py
Launch Successful!
Ignoring exception in command ping:
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\ADMIN\PycharmProjects\Fluxo\main.py", line 26, in pingme
[Button(style=ButtonStyle.URL, label="Refresh")]])
NameError: name 'Button' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'Button' is not defined
import it...
idk the import
what import is it? import button?
then why r u using it...
u haven't even imported it
nvm figured it out
await _ctx.guild.get_member(645582953434316802).send('hi')
thanks
yw
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: get_bank_data() takes 0 positional arguments but 1 was given
blah i still struggle with my error ;-; someone pls helpp
C:\Users\ADMIN\PycharmProjects\Fluxo>python main.py
Launch Successful!
Ignoring exception in command ping:
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\ADMIN\PycharmProjects\Fluxo\main.py", line 28, in pingme
[Button(emoji=self.bot.get_emoji(919616911782871061), style=ButtonStyle.grey, label="Refresh")]])
NameError: name 'self' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'self' is not defined
await ctx.send(embed=embed, components=[
[Button(emoji=self.bot.get_emoji(919616911782871061), style=ButtonStyle.grey, label="Refresh")]])
send the whole function
`import discord
from discord.ext import commands
import os
token = os.environ['TOKEN']
client = commands.Bot(command_prefix='!')
@client.command()
@commands.is_owner()
async def say(ctx, *, message):
await ctx.message.delete()
await ctx.send(message)
client.run(token,bot=True)`
Why not working
error?.......
does it even start? , and what's not working
self is not defined because you aren't in a class
It starts but not replying
do you have an on_message event?
why do you have self there?
No
||copied the code from a open source bot||
so do i just remove self?
help my error ;-;
yea it fixes your error
weird , try saving the code and running the bot again
oof does animated emojis not work for buttons?
your problem?
Not working....
:l ....
All are working but it's not replying
just fix the indentation
switching from space to tab (or vice versa) ?
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
nah, where is the problem in my code?
i mean , the error says it all
sup @upbeat otter
File "/home/allans/Bot/main.py", line 11, in <module>
client = commands.Bot(command_prefix=">", help_command = PrettyHelp, intents = intents)
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/bot.py", line 127, in __init__
self.help_command = help_command
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/bot.py", line 799, in help_command
raise TypeError('help_command must be a subclass of HelpCommand')
TypeError: help_command must be a subclass of HelpCommand
replit gives a lot of indentation errors
ye ik ._. but... where is the error :llllll
???
henlo
BHURH :ll
help_command = PrettyHelp()
line 404
a quick fix would be- reloading the website and typing it out
Sed on one helping xD
askk
read your complete error , its specified
`import discord
from discord.ext import commands
import os
token = os.environ['TOKEN']
client = commands.Bot(command_prefix='!')
@client.command()
@commands.is_owner()
async def say(ctx, *, message):
await ctx.message.delete()
await ctx.send(message)
client.run(token,bot=True)`
and the issue is?
breh, it says the ")" not the indentation :l
ty
await ctx.send(embed=embed, components=[
[Button(style=ButtonStyle.grey, label="Refresh", emoji=bot.get_emoji(919622656049967164))]])
shows this:
It's working actually but it never replies
supposed to be
Refresh
huhhh
All ok but idk why it's not replying
ctx.send(f"{message}")
not (message)
doesnt matter
yep, every argument is a string by default
Oh I see
ye
They have @is_owner, but who is the owner lmao?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: get_bank_data() takes 0 positional arguments but 1 was given
ever tried reading this?
add self as the first argument in class functions
import discord
from discord.ext import commands
import json
class Economy(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def get_bank_data():
with open("bank.json", 'r') as f:
users = json.load(f)
return users
async def open_account(self, user):
users = await self.get_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("bank.json", "w") as f:
json.dump(users, f)
return True
@commands.command()
async def balance(self, ctx):
await self.open_account(ctx.author)
user = ctx.author
users = await self.get_bank_data()
wallet_amt = users[str(user.id)]["Wallet"]
bank_amt = users[str(user.id)]["Bank"]
em = discord.Embed(title=f"{ctx.author.name}'s Balance", color= discord.Color.teal)
em.add_field(name="Wallet", value=wallet_amt)
em.add_field(name="Bank", value=bank_amt)
await ctx.send(embed=em)
def setup(bot):
bot.add_cog(Economy(bot))
the person owning the bot
yes...
they get no errors , which should be raised ..
async def self.get_bank_data()?
yes
async def function(self):
yeah I don't know why it didn't raise any error, because I don't see anything else wrong with it
is_owner is a custom function written by the person
unless I'm missing something
what time r there btw
loooooool
they would use check(is_owner) in that case ig?(im unsure)
and it wont be commands.is_owner() ofc
have they even made an is_owner function?
nu
then how does the bot know what is_owner is, they haven't even imported it and it should raise an error
iirc is_owner errors if owner_id or owner_ids is not set
Nowhere in this code they have made an is_owner func
!d discord.ext.commands.is_owner
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
pog
Just noticed, yes thank you
is the emoji in your bot's cache
still doesnt have any idea how to resolve my error :l
basic oop, every method that you create inside a class you have to use self to access it
how can I create a embed paginator? I alrd tried to read the examples from the pinned messages
don't use replit, it gives free indentation errors
outer indentation...?
Just reindent everything of you're confused
that's eh.. confusing
yes
no it isnt
A nice it works (ofc after i reload 3 times ;-;)
if you dont understand it just ask here lol
is there a way to convert the help output to list of embeds?
if yes, then it will be easy to paginate the help embed
help output?
Does this person know what spacing is
help command output*
Try don't newline function definitions, the fuck
yes
o not really sure, i just the default help command but yes you could do that technically
never even hear that term "spacing"
he means newlines
oh
but ye, the current embed is a bit too large, I alrd have a embed paginator but I don't yet know how to convert it to list of embeds (the help embed)
To organize code
is this send_page_help?
It doesn't follow any of the standard code conventions for python, but if it works then it works
it's this ```py
class MyNewHelp(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
emby = disnake.Embed(description=page)
await destination.send(embed=emby)
bot.help_command = MyNewHelp()
hm
I made that (or copied most likely) about 6 months ago so I have not touched it after that
changed discord to disnake tho
not possible to convert that into a list
oh..
you'd need to use another method, send_bot_help I think
instead of send_pages?
yes
there should be a pastebin on how to use that if you dont know how on the help command gist you got this from iirc
I assume I got it from here: https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96
yes
I did try using this https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96#paginate_help_2 but as I don't understand what is actually happening it did not work..
hm
I think it wont work if I just yeet the code (which I did)
https://github.com/Kraots/disnake_docs/blob/master/docs/pagination.py heres another example though
it's very basic
you should understand whats going on the code
there is a change i some how understand what it does but there is no way I know how to use that
just use the class and fill in the required arguments
and which one of those would be for help command?
what things can you do with interaction.response other than send_message
because i wanna add more stuff to my discord buttons :P
I suppose since I'm sure one of the methods for HelpCommand returns a list of sort
!d discord.Interaction.response
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using followup instead.
embeds = [...]
await ctx.send('a', view=EmbedPaginator(ctx, embeds, timeout=100))
``` something like this ig
so I still need to convert the help command thing to list?
technically yes
!d discord.Interaction.edit_original_message @shadow wraith?
await edit_original_message(*, content=..., embeds=..., embed=..., file=..., files=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
🤔
thanks lmao
!d discord.Message.edit
await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
that's not the right one...
get another embed object and get the message object, edit it using the embed kwarg
^^ that was for interactions
o ok
why does this not print anything? ```py
class MyNewHelp(commands.MinimalHelpCommand):
async def send_bot_help(self, ctx):
destination = self.get_destination()
embeds = []
print(embeds)
for page in self.paginator.pages:
emby = disnake.Embed(description=page)
embeds.append(emby)
await destination.send('test', view=EmbedPaginator(ctx, embeds, timeout=180))
embeds is None at first
oh
class OpenTicketButton(nextcord.ui.View):
def __init__(self, ctx: commands.Context) -> None:
self.ctx = ctx
super().__init__(timeout=None)
self.value = None
@nextcord.ui.button(label="Create a Ticket", style=nextcord.ButtonStyle.green)
async def createticket(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
ctx = interaction.user
await TicketOptions(ctx)
async def TicketOptions(ctx):
view = TicketOptionsClass(ctx)
embed = nextcord.Embed(title="Support", description="Please pick a ticket category from the dropdown below to finish creating your ticket.")
await ctx.author.send(embed=embed, view=view)
await view.wait()
if view.value == None:
await ctx.author.send("You took too long to choose! try again later.")
else:
issue = view.value
await MakeATicket(ctx, issue)
'Member' object has no attribute 'author'
hm
is sharding possible with python?
if so is there a doc on it?
show ticketoptions class/function
class TicketOptionsClass(nextcord.ui.View):
def __init__(self, ctx: commands.Context) -> None:
self.ctx = ctx
super().__init__(timeout=120)
self.value = None
@nextcord.ui.button(label="General", style=nextcord.ButtonStyle.blurple)
async def generalissues(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
if interaction.user.id != self.ctx.author.id:
await interaction.response.send_message(f"Sorry but this button isn't for you! {interaction.user.mention}", ephemeral=True)
else:
self.value = "General Issues"
self.stop()
@nextcord.ui.button(label="Factions", style=nextcord.ButtonStyle.blurple)
async def factionsissues(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
if interaction.user.id != self.ctx.author.id:
await interaction.response.send_message(f"Sorry but this button isn't for you! {interaction.user.mention}", ephemeral=True)
else:
self.value = "Factions Issues"
self.stop()
@nextcord.ui.button(label="Buycraft", style=nextcord.ButtonStyle.blurple)
async def buycraftissues(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
if interaction.user.id != self.ctx.author.id:
await interaction.response.send_message(f"Sorry but this button isn't for you! {interaction.user.mention}", ephemeral=True)
else:
self.value = "Buycraft Issues"
self.stop()
@nextcord.ui.button(label="Player Reports", style=nextcord.ButtonStyle.blurple)
async def playerreport(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
if interaction.user.id != self.ctx.author.id:
await interaction.response.send_message(f"Sorry but this button isn't for you! {interaction.user.mention}", ephemeral=True)
else:
self.value = "Player Reports"
self.stop()
class MyNewHelp(commands.MinimalHelpCommand):
async def send_bot_help(self, ctx):
destination = self.get_destination()
embeds = []
print(embeds)
for page in self.paginator.pages:
emby = disnake.Embed(description=page)
print(emby)
print(embeds)
print("Is this even ran?")
embeds.append(emby)
print(embeds)
await destination.send('test', view=EmbedPaginator(ctx, embeds, timeout=180))
``` I added a few more print, and nothin
isn't this supposed to be called on every !help command?
the error comes up in the TicketOptions function btw
nmm ctx is somehow a discord.Member instance in TicketOptions(ctx) idk how though
probably because of this
ctx = interaction.user
await TicketOptions(ctx)
oh
probably lmfao
is there a way i can fix that
just use self.ctx in the argument (ticketoptions class where you call it)
i am trying to make an open ticket button, that wont work
you can make the class have extra arguments though
it will just use the ctx value for the person who ran the command to get the embed with the button up
is sharding possible with python yet?
!d discord.ext.commands.AutoShardedBot
class discord.ext.commands.AutoShardedBot(command_prefix, help_command=<default-help-command>, description=None, **options)```
This is similar to [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") except that it is inherited from [`discord.AutoShardedClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.AutoShardedClient "discord.AutoShardedClient") instead.
it always was
hey i am trying to make a bot.wait_for
the command is working good its just an error is coming
codes:
@bot.listen()
async def on_message(message):
if message.content.startswith('s!satan'):
channel = message.channel
embed = discord.Embed(title="WARNING:", description="**After Reading Anyone Of These Doujins,You May Ask Yourself Question such as\nWhy?,What I Just Read?,Am I Okay?,etc\n(Hand Picked By Creator-sama)**")
embed.set_footer(text='Type CONFIRM To Read')
await channel.send(embed=embed)
def check(m):
return m.content == 'CONFIRM' and m.channel == channel
with open('satan.txt', 'r') as f:
lines = f.readlines()
g = random.choice(lines)
msg = await bot.wait_for('message', check=check)
await message.channel.send(g.format(msg))```
error:
return m.content == 'CONFIRM' and m.channel == channel
NameError: free variable 'channel' referenced before assignment in enclosing scope
Every time I type !help isn't the class called?
did you add
help_command=None in the prefix statement code?
No I added the help command a different way, let me find it
like dis
bot = commands.Bot(command_prefix="!", intents=intents,help_command=None)```
bot.help_command = MyNewHelp()
hmmm why dont you make a new command named help and run that function in the command itself?
I don't think that's a good way
but shouldn't that class be called everytime I type !help
RuntimeError: Concurrent call to receive() is not allowed
what does this error mean? I'd send the code but it doesn't say what's causing the error
hmm i actually dont know much about classes
i tried to help as possible
an instance of the class will be called iirc, yes
hmm why does it not print anything then?
do someone know whats dis called?
how can i make an eval commad??
!d exec
exec(object[, globals[, locals]])```
This function supports dynamic execution of Python code. *object* must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1](https://docs.python.org/3/library/functions.html#id2) If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section [File input](https://docs.python.org/3/reference/toplevel_components.html#file-input) in the Reference Manual). Be aware that the [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal), [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield), and [`return`](https://docs.python.org/3/reference/simple_stmts.html#return) statements may not be used outside of function definitions even within the context of code passed to the [`exec()`](https://docs.python.org/3/library/functions.html#exec "exec") function. The return value is `None`.
!d eval
eval(expression[, globals[, locals]])```
The arguments are a string and optional globals and locals. If provided, *globals* must be a dictionary. If provided, *locals* can be any mapping object.
@devout iris
i saw dis in a discord button
!d discord.ButtonStyle.link
Represents a link button.
This?
I have no…oh
No
It won’t work
For a discord bot
You have to do something like stdout or whatever tylerr said
It will only print the evaluated code, but when sending the result it returns None
Welcome back to the discord.py series! Here's a overwhelmingly requested command :D
Read description for links!
----------------------------------------------------------------------------------
Need Help?
Require help with your code? Why not head on over to our dedicated support discord where you can receive only the best support: https:...
.bm
Thanks Caeden, I needed that as well
Me who made an eval without any tutorial: 😐

Why is nothing printed when I run !help
Sweet, you used eval()?
Why did you do embeds.append?
Does that actually work?
@tawdry perch
It was supposed to create list of embeds
Ah~
In theory it could work
Ah no
Nothing
Oh
Not even the text
ye
@hollow quarry is sharding possible in dpy yet?
greetings Eevee
yes
Hi dear
stop being so sus
--is there a docs on it?--
lol, wait
Please don't ping anyone for help. And I have no idea, I don't use discord.py.
Ok
Does your EmbedPaginator expect context? Because ctx here is actually a mapping of your bot's commands
It isn't actually context
mistakes happen
ok
Yes it does expect ctx
thanks
my pleasure
Ok, well like I said ctx here is actually a mapping of your commands. Not a commands.Context object
Oo, let me try that in a while
my condolences
smh
Hello
so I can just do this? ```py
ctx = HelpCommand.context
@commands.has_permissions(manage_messages = True)
async def purge(ctx, amount=2):
await ctx.channel.purge(limit=amount)```
members without perms can purge.Why?
oh
HelpCommand is the class, you want the instance
Since your subclassing it, you have a HelpCommand instance inside of self
Interesting
so I have to do self.context?
anyways, best of luck
yes
oh
now I have this, but nothing is being printed ```py
class MyNewHelp(commands.MinimalHelpCommand):
async def send_bot_help(self):
destination = self.get_destination()
embeds = []
print(embeds)
for page in self.paginator.pages:
emby = disnake.Embed(description=page)
print(emby)
print(embeds)
print("Is this even ran?")
embeds.append(emby)
print(embeds)
await destination.send('test', view=EmbedPaginator(self.context, embeds, timeout=180))
bot.help_command = MyNewHelp()
which is mapping?
Yes,
and what does that mean?
And in the snippet you just sent you only have self
anyone answer my problem pls
Where is the another argument this method takes???
uh nowhere
@pliant gulch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: foo() takes 1 positional argument but 2 were given
I see, but what is mapping? Like what do I need to do with it
Mapping is a list of your bot's commands
You can do whatever withit
For mine I used it to format my help embed
hmm so if I just pass it to the help command but I don't use it, it should be ok?
still nothing in console
The prints don't showup?
class MyNewHelp(commands.MinimalHelpCommand):
async def send_bot_help(self, mapping):
destination = self.get_destination()
print(mapping)
embeds = []
print(embeds)
for page in self.paginator.pages:
emby = disnake.Embed(description=page)
print(emby)
print(embeds)
print("Is this even ran?")
embeds.append(emby)
print(embeds)
await destination.send('test', view=EmbedPaginator(self.context, embeds, timeout=180))
``` this is what I currently have
it prints nothing
You probably are erroring somewhere else as well then ¯_(ツ)_/¯
Or it's stalling somewhere
Hey does anyone know of a surefire way to check message contents for exploits/attempted code injections/abuse. Basically a generic reliable message sanitizer
when I do !help it has no arguments, right?
@commands.command()
async def uptime(self, ctx:Context):
delta_uptime = datetime.utcnow() - self.bot.launch_time
hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
days, hours = divmod(hours, 24)
return await thebed(ctx, '', f"I've been Up since **{days}** Days, **{hours}** Hours, **{minutes}** Minutes, and **{seconds}** Seconds!")
i'm not using classes :/
guys anybody now why does it can't recognize "message"? maybe i need to import something?
you get the idea from that, right?
thats all i got
yep
u didn't pass message, that's why
just remove self from vars and use bot commands structure
pass the message kwarg
and users also?
no
u have to define users
now i have another problem)
indent?
did you just copy paste it..
yes your indentation is incorrect @proven osprey
oh my bad
i'll edit it but the basic things are not working
such as?
oh those yellow lined things
you can remove typehint from ctx, or do ctx: commands.Context (iirc)
and thebed seems to be a custom function so use normal ctx.send
why
what?
why did you say that? I thought u misunderstood what I said
eh forget it, I can't even try explaining it
okay
@commands.has_permissions(manage_messages=True)
async def purge(ctx , amount=2):
await ctx.channel.purge(limit=amount)```
members without perms can purge msges pls tell how to fix thi
@quick gust
show your code, can you?
yep a sec
Are you sure they can?
It should be working fine
yeah i tried it with my alt
are you using classes? like cogs?
nope
Did you reload your bot?
yep
also, remove ctx from ctx.send("") remove ctx from inside ()
Yep, it should be bot.command() instead
remoce ctx, from inside it, also the empty ''
seems better
@final iron is something wrong with my code?
i'm gonna try now
Doesn't look like it
So why is the purge thing happening without perms
I have no idea
I checked the perms in the role
datetime.datetime.utcnow
I think their naming was a bad idea
With datetime being the module and datetime also being a class
yeah it's wack
?
like that?
Yes
Im now wondering if you import datetime from datetime what happens if you're trying to access a class from the module and not a function from the datetime class
stilll same
You didn't reload your bot
The error is showing code thats not there
Is that from another place in your code?
k
how to know whats a cmds cooldown?
that won't affect anything
but sitll same
I know but theres no point
yep
Its redundant code
well why care about it if it does nothing
not gonna argue over this but no need to spot-light that
i'm sure you did import datetime right?
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
yes
💀
how can i seperate the values? im trying to put them into objects like bot.get_guild() bot.get_channel() and bot.get_role()
its from datetime import datetime
not that
i'll try
from datetime import datetime instead of import datetime
for me it works without that
:skul:
looks good
ehh
when you do bot = commands.Bot(…) you need to also do bot.launch_time = datetime.utcnow()
copy and pasting code isn’t the best
It is useful for IDEs with Intellisense. Without type hinting it to commands.Context the IDE doesn't know from what class ctx is from and it won't suggest anything.
yes and after that you do bot.launch_time = datetime.utcnow()
ahh smhh
Learn Python ❎ Go slowly ❎ Copy and Paste ✅ Ask questions and not understand the answer ✅
yes.
i just should learn dpy
cus i know basic python i guess 😄 (except OOP and a few funcs)
ok thats a good start at least
did you save it and restart?
if youve done it like this it should be fine
i'm already doing this always
how can i seperate the values? im trying to put them into objects like bot.get_guild() bot.get_channel() and bot.get_role()
i swear bot.launch_time is a thing how is it not working or you
its not.
i might have mistyped
:troll:
it isnt a thing.
:p
oh then doesn't that solve ahmet's brain problem? 💀
lol really i'm savinggg
okay i'll shutdown my bot fully and i'll restart from 0
u can see
this adds the attribute launch_time to bot. so when you access bot it would have the attribute launch_time
youve just fucked something up
guild = bot.get_guild(configured[0][0]), get_channel(configured[0][1])
etc
lmao
ty
what can be if i add this to bot veriable?
ok remove from datetime import datetime and do - datetime.datetime.utcnow()
like old?
yes youve changed something
you keep changing shit
remove from datetime import datetime
btw i wasn't change this func when i add new veriable
if i remove this i won't change anything in this func
did u understand me or not?
no i dont understand at all
most ineffecient code ever?
@bot.command()
async def eliminate(ctx, member: discord.Member):
guild = member.guild
SSCompetitor_Role = guild.get_role(919570782185750578)
if ctx.channel.id == 919563757204693103:
if guild.get_role(919571300467474543) in ctx.author.roles:
if guild.get_role(919570782185750578) in member.roles:
await member.remove_roles(SSCompetitor_Role)
await ctx.send("{0} was eliminated! R.I.P".format(member.name))
else:
await ctx.message.delete()
ah
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Naming conventions 
me?
yes
there is a lot of things in this file wait a bit
Hey @devout iris!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
ah lol right
ok dont do anything i dont tell you to do. change bot.launch_command = datetime.utcnow() to bot.launch_command = datetime.datetime.utcnow()
after you do this save, turn the bot off and restart.
alr
ok.
yeesssss
np.
@commands.Cog.listener()
async def on_member_join(self, member):
await self.update_totals(member)
await self.bot.db.commit()
inviter = await self.tracker.fetch_inviter(member)
await self.bot.invites.upsert({"_id": inviter.id, "joiner_id": member.id})```
AttributeError: 'Bot' object has no attribute 'invites'
before we continue, is this code copy and pasted?
wym
did you type this code out, letter by letter?
nope, one of my friends made it a while ago, and it broke, but i dont understand it well
so can you help?
@commands.command()
async def verc(self, ctx):
configured = var.execute("SELECT * FROM verification WHERE guildid = ?", (str(ctx.guild.id), )).fetchall()
guild = self.bot.get_guild(configured[0][0])
channel = self.bot.get_channel(configured[0][1])
role = self.bot.get_channel(configured[0][2])
await ctx.send(configured)
await ctx.send(f'{guild} {channel} {role}')```
@commands.Cog.listener()
async def on_guild_channel_update(self, before, after):
async with aiohttp.ClientSession() as session:
async with self.db.execute(
f"SELECT webhook, guild_id from 'logging' where guild_id = {before.guild.id}",
) as cursor:
config = await cursor.fetchone()
if config is not None:
webhook = Webhook.from_url(config[0], adapter=AsyncWebhookAdapter(session))
if before.guild.id == int(config[1]):
async for entry in before.guild.audit_logs(action=discord.AuditLogAction.channel_update,
oldest_first=False):
embed = discord.Embed(
description=f'Channel was updated ({after.mention})',
color=discord.Color.dark_theme()
)
embed.set_author(name=entry.user, icon_url=entry.user.avatar_url)
embed.timestamp = datetime.datetime.utcnow()
embed.set_footer(text=f'{self.bot.user}', icon_url=self.bot.user.avatar_url)
embed.add_field(name='Creation date', value=f'<t:{round(before.created_at.timestamp())}:D>',
inline=False)
if before.overwrites:
embed.add_field(name='Overwrite deleted',
value=f'For: role Undefined',
inline=False)
if after.overwrites:
embed.add_field(name='Overwrite created',
value=f'For: role Undefined',
inline=False)``` why is the field not added although I add a role to a channel
are you sure you got the channel and guild the right way around? also, you did role = self.bot.get_channel(configured[0][2]). did you mean role = ctx.guild.get_role(configured[0][2])?
right, ill fix that
weird, Command raised an exception: AttributeError: 'Bot' object has no attribute 'get_role'
@manic wing so can you help me?
role = self.bot.get_role(configured[0][2])
oh ctx.guild
the bot object does not have a get_role method.
@commands.command()
async def verc(self, ctx):
configured = var.execute("SELECT * FROM verification WHERE guildid = ?", (str(ctx.guild.id), )).fetchall()
guild = self.bot.get_guild(configured[0][0])
channel = self.bot.get_channel(configured[0][1])
role = ctx.guild.get_role(configured[0][2])
await ctx.send(configured)
await ctx.send(f'{guild} {channel} {role}')```
are you sure [0] is the guild id and not the channel/role id?
sorry, no
Remember that ids are ints not strings
ohhh shit i didnt see it was a string
you're a genius man 🙇
lmao
You should generally be storing them in the database as (big)ints as well
in the code above, its formatted like this
var.execute("CREATE TABLE IF NOT EXISTS verification(guildid TEXT, roleid TEXT, channelid TEXT)")
var.execute("INSERT INTO verification(guildid, roleid, channelid) VALUES (?, ?, ?)",
(str(ctx.guild.id), str(role.id), str(channel.id)))```
oh wait
stahp changing everything to strings
ok i updated to py @commands.command() async def verc(self, ctx): configured = var.execute("SELECT * FROM verification WHERE guildid = ?", (str(ctx.guild.id), )).fetchall() guild = self.bot.get_guild(configured[0][0]) role = ctx.guild.get_role(configured[0][1]) channel = self.bot.get_channel(configured[0][2]) await ctx.send(configured) await ctx.send(f'{guild} {channel} {role}')
same output
i changed the order
we said INT
INTTTTTTTTTTTTTTTT
so (int(ctx.guild.id) for examlpe?
int(configured[0][0])
ohhi sse
jeeeeeeezus
int everything
The field in the database is a TEXT field
It doesn't matter how you insert it
It will always be returned as string.
So instead of acting like that you could tell that person to use BIGINT in the database structure
inviter = await self.tracker.fetch_inviter(member) await self.bot.invites.upsert({"_id": inviter.id, "joiner_id": member.id})
AttributeError: 'Bot' object has no attribute 'invites'
well now it returns the names
Instead of acting childish and almost insulting them..
Thats because I'm NOT 10
I wouldn't joke about being 10 years old
Fine. 14
this is for a verification configuration, how can i use that to get a guild, channel and role
this is against tos to say, id delete it if i were u
That's because you sent the names of each of them.
too late
@manic wingbro do u know how can i make an if condition for "if minutes == 0 or if hours == 0 .... bot won't show it in answer"
XD
lol
right, forgot the id attr
inviter = await self.tracker.fetch_inviter(member) await self.bot.invites.upsert({"_id": inviter.id, "joiner_id": member.id})
AttributeError: 'Bot' object has no attribute 'invites'
you've said this multiple times and noone is helping because noone knows what invites is supposed to be...
If you copy code from GitHub or somewhere else, then copy it in its entirety at least..
he said his friend wrote it for him
@commands.Cog.listener()
async def on_guild_channel_update(self, before, after):
async with aiohttp.ClientSession() as session:
async with self.db.execute(
f"SELECT webhook, guild_id from 'logging' where guild_id = {before.guild.id}",
) as cursor:
config = await cursor.fetchone()
if config is not None:
webhook = Webhook.from_url(config[0], adapter=AsyncWebhookAdapter(session))
if before.guild.id == int(config[1]):
async for entry in before.guild.audit_logs(action=discord.AuditLogAction.channel_update,
oldest_first=False):
embed = discord.Embed(
description=f'Channel was updated ({after.mention})',
color=discord.Color.dark_theme()
)
embed.set_author(name=entry.user, icon_url=entry.user.avatar_url)
embed.timestamp = datetime.datetime.utcnow()
embed.set_footer(text=f'{self.bot.user}', icon_url=self.bot.user.avatar_url)
embed.add_field(name='Creation date', value=f'<t:{round(before.created_at.timestamp())}:D>',
inline=False)
if before.overwrites:
embed.add_field(name='Overwrite deleted',
value=f'For: role Undefined',
inline=False)
if after.overwrites:
embed.add_field(name='Overwrite created',
value=f'For: role Undefined',
inline=False)
await webhook.send(emebd=embed)``` why is the field not added although I add a role to a channel
Then talk with your friend about it.
oh okay, im not sure what its supposed to be..
i lost contact with him
i can give u the pastebin link if you canm help
nor do we lol
can i dm you the pastebin?
can you not just send it here?
okay
if you just wanted to have it work in pycord, probably just replace every single word discord with pycord
through your ide
just mass replace all
yes...
just every single occurance
here
embed = discord.Embed(title=f'Verification', description=f'You have `1` attempt to verify. If you fail, you may be re-evaluated by executing the command again', color=clr)
IndentationError: unexpected indent```
weird
Pycord changed the import?
Doesn't seem like they did from a quick glance at the GitHub
whats the import? never used pycord lol
if this is inside a class why is @commands.command indented twice?
its not
thats 1 tab (4 spaces)
oh true
well now for some reason it works
¯_(ツ)_/¯
have you seen why @manic wing ?
how do i delete a message with its id
no
what variables do you have? channel?
ah what do you think it cxould be?
not a clue
class MyNewHelp(commands.MinimalHelpCommand):
async def send_bot_help(self, mapping):
destination = self.get_destination()
print(mapping)
embeds = []
print(embeds)
for page in self.paginator.pages:
emby = disnake.Embed(description=page)
print(emby)
print(embeds)
print("Is this even ran?")
embeds.append(emby)
print(embeds)
await destination.send('test', view=EmbedPaginator(self.context, embeds, timeout=180))
``` this is what I currently have, but it does not print anything/paginate the embed, why?
Hey there, I changed my d.py bot to work with multiprocessing but every time I execute a command it stops after giving the final output... Does anyone know about that issue?
is ctx.send_message a thing anymore?
I'm trying to dm a specific person whenever a command is run..
just grab the user, using a member object. then use member.send()
!d discord.Member.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
no, its not a thing @abstract kindle
yeah says ctx has no attribute member
show me your code.
so how would I send a message to a specific person? I know how to send a DM to the author of the previous message using ctx.author.send
username = await self.bot.wait_for(event="message", timeout=30.0)
owner = self.bot.get_user(326903703422500866)
await ctx.Member.send(owner, username)
bot.get_user() returns the discord.User object not the discord.Member object
it would be await owner.send()
no problem.
@commands.command()
async def verify(self, ctx):
member = ctx.author
def check(m):
return m.author == ctx.author
configured = var.execute("SELECT * FROM verification WHERE guildid = ?", (str(ctx.guild.id), )).fetchall()
vguild = self.bot.get_guild(int(configured[0][0]))
vrole = ctx.guild.get_role(int(configured[0][1]))
vchannel = self.bot.get_channel(int(configured[0][2]))
if ctx.guild.id == vguild.id:
if ctx.channel == vchannel.id:
role = ctx.guild.get_role(vrole.id)
ctx.message.delete()
#more code
if role in member.roles: #UnboundLocalError: local variable 'role' referenced before assignment
alr = discord.Embed(title='Verification', description=f'You are already verified!', color=0x2f3136)
await ctx.send(embed=alr, delete_after=5)
return``` error is on the line it errors on
your role variable is inside an if condition; if ctx.channel == vchannel.id:. so the role variable can only be used if this if condition returns a Truethy value. your if role in member.roles: statement will be invalid because then role is undefined.
one sec, ill show something relitivant to this
