#discord-bots
1 messages · Page 929 of 1
and not filter butt
just reminding you that it's optional 😡
.bm

thank you
it filtered "it" and "blo"
i tried to find a package for this but only found a couple that did not support leetspeek
arent you experienced enough to show examples with it?
not on mobile
your point?
examples of what?
examples with return annotations
need me to teach you okimii?
you do know i already know return annotations? you should use your scrollwheel its useful👍
i'm just your average skid on mobile, i don't know what annotations are 
unfortunately my cellular device does not have a scroll wheel
why annotations are?
swipe up
iirc okimii is talking about
def my_func() -> str:
return "my string"
obviously
yes return annotations 
and kayle knows hes just too lazy/hes on mobile
Then why did you say you don't know what annotations are 🗿
lazy
Erotic
I suppose that the webhook is taking input from a text channel where someone said "lol"?
Oh ok
You did elses with exceptions
You should try doing
try:
# Code
except ValueError:
# Code for ValueError
except Exception:
# Code for any other error
That should work
that's interesting
controlling the discord bot from a panel seems like such a creative idea
ye that's pretty cool
thx
Nothing pops out?
You replaced the comments with the code to execute right?
It doesn't pop out no message box?
how to set embed color in hex format?
that's strange
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.
Try doing a message box outside all the exceptions to see if code is running correctly
Like a debugging message
I don't think so
try removing the Exception
At the second except
And btw try putting the except with no Exception at the end of the exceptions
I don't know if I'm explaining well
Why is it
Do NOT do this
its only bad if you catch and unknown error and ignore it but if you catch it and do an action your fine
it catches BaseExceptions and Exceptions
and you generally don’t want to catch the system exiting exceptions
Ohh like KeyboardInterrupt
how to obtain interaction endpoint url?
please except the exact error
if you want to handle multiple errors, do multiple except blocks or
except (ExceptionsHere)
are the exception groups out?
idk
anyone?
Wrong one
i forgot the num of the pep
!pep 654
I’m guessing HTTPException
no one replied, sad
Can someone help me,
I am trying to code my ticket bot to get the list of users that had sent a message in the channel which will need a db
But I am not quite sure on how to do it
sounds like a cool idea, whats the issue?
I don't have an idea on how its done.
I have browsed through but have no clue
I thought someone here has experience on this and could explain
whats your experience with discord bots?
this may prove to be harder than necessary without experience
cant you just use TextChannel history?
?
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
Let me find it
Hm seems AsyncIterator has been removed
I think you can just do
messages = [m async for m in channel.history(limit=...)]
To get a flattened list of messages
you can flatten it just fine
Then to get the users that have sent a message in the channel
!d discord.Client.get_channel
bot.get_channel(id) returns a Messageable object
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
Just use channel.send() after that.
If you don't have it cached, then you have to some unconventional stuff with HTTPClient, which is against the design language of dpy.
so ```py
channel = self.bot.get_channel(id)
channel.send(embed=embed)
im running it in a cog
Try it
send is a coroutine aka you await it
Might wanna check if channel is None too, which is the case if it's not cached.
fetch_channel exists
how does the cache work
as in why would the channel not be cached
under what circumstance does it become cached
you dont want to get in to that
It's an API call, I tend to advise people not to make them unnecessarily.
I was assuming that AsyncIterator was only for backwards compatability, now that is is removed does that mean discord.py did a version bump?
its the only option second to get_channel...? what unconventional stuff were you proposing to do with HTTPClient?
all the functions you would want to do would be available to you through the bot
discord/http.py line 590
def send_message(```
nice, thanks! worked! i was doing a wrong attribute
good luck passing params
Kind of weird for it to be a NamedTuple imo
How?
discord/abc.py line 1403
with handle_message_parameters(```
bit of a pain in the ass having to use this as a user
Because you could just make a "master" dict, then add all your keys, etc
a singular api call probably isnt worth the chaos you would need to pass that shit
"All that shit"?
You literally only actually need params.payload
And it can be a {'content': ...} dict
Maybe Danny wanted the file cleanup
With the __exit__() method of the named tuple.
different story for files
It seems to me, the main reason of doing this was for form data, but an extra parameter in the signature would've done just fine tbh
Not that it matters much although
But like I said, still unconventional. Not a major PITA tho.
you're right, it isnt all that hard to pass your own payload, but its unconventional and probably wouldnt be worth the hassle to just make a singular api call
considering more than most of the people you would recommend the 'unconventional stuff with HTTPClient' wouldnt understand the half of what is going on
No actually, I don't know why I brought up the http client. I don't generally recommend it at all.
discord.py's RESTful interface could've been a lot better
One of pythons selling points is hackablity imo
It would've been niced to have the option to use the HTTPClient in a sane way
Well, it's internal so I guess we all have to just sit back and cry
At least me, I would have loved a more stateless client.
I still don't understand lookup complexity or whatever it's called so this makes zero sense to me
I've never actually tried to learn about it
I might now
O(n) means linear, time. Time is dependent on dataset size
There for if we have 10 oranges, it takes me longer time to count them, compared to 5 oranges
Oh yeah definitely, ConnectionState._get_message() is atrocious.
discord.py could've had an O(1) message cache, meaning constant time. Therefor if I had 10 oranges, it would take same time to count them as the 5 oranges from earlier
dicts are ordered, they could've just impl __setitem__ to pop
def _get_message(self, msg_id: Optional[int]) -> Optional[Message]:
return utils.find(lambda m: m.id == msg_id, reversed(self._messages)) if self._messages else None
Danny wtf
At least he reverses it
And they are ordered!!!
My own impl already has it 😼
how do I check if a channel is a textchannel?
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
!e
str_var = "my string"
if isinstance(str_var, str):
print("a")
@final iron :white_check_mark: Your eval job has completed with return code 0.
a
@rocky trench
Thx
Thx
You ever work on something dumb for way too long
i think i finally got my dash generator to actually get equal length strings for discord
test - - - - - - - - - - - - - - - test
longer test - - - - - - - - - - test
even longer test - - - - - - -test
$sym0Ls[]&stuff - - - - - -test
Willing to share the code?
from PIL import Image, ImageFont, ImageDraw
discord_font = ImageFont.truetype("WhitneyBook.ttf", 1600, encoding="unic")
def dash_gen(string):
length = discord_font.getsize(string)[0]
while length < 16820:
if length < 16820:
string += " "
length += 362
if length < 16709:
string += "-"
length += 582
return string
then i got a big ass dictionary with all the character sizes
Interesting
await message.channel.send("LOL",
What argument should I add to mention a specific user?
You wouldn't use an argument
<@USER_ID>
How about replying?
!d discord.Member.mention
property mention```
Returns a string that allows you to mention the member.
i think there may be an ! in there somewhere
!d discord.Message.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
It's a different method
I am not sure I understand. How do I add the author id?
Also could you complete the code, please?
!d discord.Member.id gives you the id
property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.id "discord.User.id")
I want to enter the id myself.
Like have the command take an id param?
Not going to spoonfeed you code
That's not what this server is for
xD
I want to input the author.id myself.
How do I do that?
Like in a command?
Just make an id param in the command function
If you typehint the argument as discord.User, it supports both id and user mention
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("LOL") and message.author.id == :
await message.channel.send("LOL",)
This is my code.
That's not a command, it's an event.
I was hoping to learn commands too.
So far we've made a pretty simple bot - it only responds to !hello with a static response. Not particularly interesting, is it? Let's fix that! In this part we'll be creating a ping command that shows the bot's gateway websocket latency when you call it.
!d discord.Member.id gives you the id
How do I put the messages of a bot in an embed message, could someone help me?
Use the discord.Embed class to make an embed and use the embed kwarg in . send () while sending it
thx
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
would this be ok?
the tiny bit the length is off is making me mad
Why not just use fields?
Then name will be the item
because mobile is dumb and puts each field on a new line
Doesn't seem like a big deal to me
Nah like create a different field for each item
looks awful and takes up too much space
how can i make it so if the user answers too fast it says something like, dont copy and paste that!
i've tried literally every option, dashes is for some reason the best
Would this be alright, handsome guys?
well since you called me handsome?
xd
would it be alright for what
is it well programmed?
my definition of well programmed is whether it runs
Is this a user error? errors.ConverterFailure(*args: t.Any, opt: commands.base.OptionLike, raw: str)
yes
If a converter fails it's the users fault? I feel like it is?
BRUH
Are you writing this in a single file or separate from the main thing
a single file
I'm using hikari. I don't know the library you're using sorry. A good thing to do is go back and look at your other commands that work
F
Do you have other commands that work?
😆
They're using discord.py
if its hikari-lightbulb it means the argument provided by user is not the the argument the option accepts
NRUH
Yeah, I thought so. Its a user error. Thanks. I don't mind the pings.
anyone know how to delete all channels in a discord server with a command
it can be, but is not limited to a user error, any factor causing the argument to not get converted to that required class can cause that error
can anyone help me?
can anyone help me
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
you can save what time the bot's message was sent ```py
message = await send("the message bot sends")
then wait for that message
response = await wait_for("message")
and then substract the difference between message creations
difference_timedelta = response.created_at - message.created_at```
i need help cuz a server got raided and i'm trying to delete all the channels tryin to do the oppsoite atm
and then check that timedelta on your own convinience
( i just mentioned the methods as a pseudocode, before someone gets mad)
how to fix this guys :,,,,,v
bot.remove_command('help')
or help_command=None
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="YOUR PREFIX")
bot.remove_command('help')```
case sensitive lol
and dont make your own help command if you plan to.
HelpCommand walkthrough
https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96
consider subclassing discord.ext.commands.HelpCommand instead
this
if you are using client replace it with bot
what
nah this is simpler
yea probably lol
🧢 probs
no just use the kwarg
jeez ok
!d discord.ext.commands.Bot.help_command
The help command implementation to use. This can be dynamically set at runtime. To remove the help command pass None. For more information on implementing a help command, see Help Commands.
i prefer to use the old methods so dont mind me

you got a problem with that 
I shall do this to you
ok back to bot discussion
yes
how to color the whole codeblock red
yeah pov you added 69 commands and you gotta manually add it in your horrible help command
why tf did it not reply
use this py for command in bot.walk_commands(): description = command.description if not description or description is None or description == "": description = "No Description Provided" embed.add_field(name=f"!{command.name} {command.signature if command.signature is not None else '' }", value=description) #, value=description
be smart
that way you only have to add description in decorator
if not description already covers description being ""
Same with it being None, your other part of the if statement is use-less 100%
yes but its just to make sure
Computers don't mess this up 🤔
but idk
And you could remove your ternary condition inside of the f-string
Using just or
This would give a speedup
True
Andy can you optimize my life 😔
anyone know json here
no
😡
Just ask your question
Don't know why you posted it in there as json isn't a database
its kinda considered a database
jeez ok
yes and you do that in the subclassed HelpCommand
though you could just use Context.clean_prefix to replace !
json is more like a dict but with less options.
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
yeah
true
You still need help? Don't think the officer helped you out.
wtf is wrong with panda
as in pep8?
if he doesnt know since people dont want to help me because using json is a bad idea but idc
Throw in the questions I'll have a look.
Fits on one screen now woo
I know something about json, I don’t know if I will be able to help
lookie in #databases
Why the command is not working?
Do you got an error?
no
i beg that you’re doing bot.run
lol yes. How should i do it?
you’re … not calling bot.run?
oh no no I am calling it and the code in :
@bot.event
async def on_message(message):
works perfectly. Only the commands don't work
replace .event to .listen()
Do all commands not work?
Does that even work? I mean ur code has discord.Client n discord.ext.commands.Bot

bot just gets overwritten, works as normal.
!e
x = 0
x = 1
print(x)
@manic wing :white_check_mark: Your eval job has completed with return code 0.
1
Oh i see
as panda rightly said, if a variable is redefined nothing happens to the previous definition
Welp tnx
yes
I added discord.Client because it didn't work at first
Could you show some more code I don't think the problem is here.
!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.
that fixes everything
lol
i i dont think so


lol
Caeden is typing...
didnot work too
R.I.P
yes rip indeed
bot = commands.Bot(command_prefix = '%')
@bot.event
async def on_ready():
print('logged in as {0.user}'.format(bot))
@bot.listen()
async def test(ctx, arg):
await ctx.send(arg)
#*respond to messages
@bot.event
async def on_message(message):
msg = message.content
user = message.author
if user bOt.UsEr :
ReTuRn
If MsG 'test':
await message.channel.send('test worked')
bot.run(token)
that emote name is questionable
what did i tell you to do.
read exactly what i told you to do.
the on message works
Remove the on_message and try again.
Where? sorry I don't know what you mean
.
in the on_message, replace .event to .listen().
i didnt say .command() to .listen().

Patience is needed, he is obviously a beginner and cannot read instructions.

where did u get the code from?
who said im not being patient?
and perhaps beginners shouldnt use discord.py
still
just saying
yeah soryy
But it still is not working
send the code
what i said, works. what you did, didnt work.
do you have the bot in the server
there is a difference
Do u even know python or u just testing
The syntax is wrong
can u give a link?
Did u import anything even?
what tf
bot = commands.Bot(command_prefix = '%')
@bot.event
async def on_ready():
print('logged in as {0.user}'.format(bot))
@bot.command
async def test(ctx, arg):
await ctx.send(arg)
#*respond to messages
@bot.listen()
async def on_message(message):
msg = message.content
user = message.author
if user bOt.UsEr :
ReTuRn
If MsG 'test':
await message.channel.send('test worked')
This is what you said right?
not working
Is that the whole code?
Also please use this
yes
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
yea!!
There are no errors and the syntax is good
dont forget @bot.command should end with parentheses ()
bot = commands.Bot(command_prefix = '%')
@bot.event
async def on_ready():
print('logged in as {0.user}'.format(bot))
@bot.command()
async def test(ctx, arg):
await ctx.send(arg)
#*respond to messages
@bot.listen()
async def on_message(message):
msg = message.content
user = message.author
if user == bot.user :
return
If message.content == ('test'):
await message.channel.send('test worked')
I forgot to added back
I AM SORRYYY
Thank you all
@manic wing sorry again and thank you
I do recommend making commands instead of checking for messages.
I just fixed the code for MEMAN
Its not mine
Yes this is my plan i was just testing
Thank you
Oh wrong reaction :3
Thank you
Sorry for making you get mad lol
whos mad?
Im not mad i was just saying u made a mistake
🤨
Pretty funny way of saying it~
That was a question
IT hurt my feelings but it's okay i deserve it 
Take out the "even" next time it can come over as rude :)
You helped out anyways 👍
You do not deserve to have your feelings hurt.
Sorry
:)
Ignoring exception in command suggest:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 185, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\youse\Downloads\Airline\DiscordBots\FlyAscent\Embed bot\main.py", line 64, in suggest
title = {ctx.author.username},
AttributeError: 'Member' object has no attribute 'username'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\bot.py", line 1182, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 904, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 194, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'username'
can yall help me with this??
this is the code
It's just name
so just name?
nickname is .nickname
yep
i want it to be like seff<33#9999
str(member)
btw you can use a list instead of a dict (it appears you dont really have a value for the dict value)
wym
it would be ctx.author not member
author gives me an error
what error?
from discord.ext import tasks
@tasks.loop(hours=1)
async def send_message():
... # send message
send_message.start()```
Microsoft Windows [Version 10.0.19044.1586]
(c) Microsoft Corporation. All rights reserved.
C:\Users\youse\Downloads\Airline\DiscordBots\FlyAscent\Embed bot>python main.py
Ignoring exception in command suggest:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 185, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\youse\Downloads\Airline\DiscordBots\FlyAscent\Embed bot\main.py", line 64, in suggest
title = message.author,
AttributeError: 'str' object has no attribute 'author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\bot.py", line 1182, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 904, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 194, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'author' @cloud dawn
These are the docs pretty well explained, if you got more questions you can ask here.
its ctx.author, not message.author
str(ctx.author)
remove srt(member) and put f‘{ctx.author}’
This got more confused than needed lol
The f outsied
eh preference
well a dictionary is useful because it can store a key and a value, if you dont need the value you may want to just use a list
I feel like I know you
oh str(ctx.author)
I'm off to bed 👋
goodnight panda
Gn
No les molesta que hable español?
please try to speak english to the best of your ability
Ñ
Te molestan que hables español.
||They do bother you speak spanish.||
good morning panda
Hablas español
Gn guys ima go
It was a small joke please follow Caeden's request.
👋
Ñ por si acaso
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
Please use English @cunning garden
Ok
glotech
how would I grab the content of a message that is code formatted
I'm trying to make it so the eval command runs even if you try to eval it in code format
Nevermind, I just had the bot strip the ` characters
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
so how would you do it
like do you just put exactly what’s there
Wdym
embed.set_footer(name=ctx.author, icon_url=ctx.author.avatar_url if ur in v2 then avatar_url would be avatar.url
After u define embed
so under embed = discord.embed?
Yea
okay one sec
gnnnn
No it should be outside the parenthesis. Just create a line above get_channel and put it there
ah ok
embed methods like set_footer can be tacked onto the end of the embed definition
Or that but in my opinion it looks odd
outside of paranthesis, so put it above channel
Ignoring exception in command suggest:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 185, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\youse\Downloads\Airline\DiscordBots\FlyAscent\Embed bot\main.py", line 70, in suggest
embed.set_footer(name=ctx.author, icon_url=ctx.author.avatar_url)
AttributeError: 'Member' object has no attribute 'avatar_url'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\bot.py", line 1182, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 904, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 194, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
avatar.url
e.g. py embed = discord.Embed( title='...' ).set_author( name='...' ).set_footer( text='...' )
huh, less lines :D
Ignoring exception in command suggest:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 185, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\youse\Downloads\Airline\DiscordBots\FlyAscent\Embed bot\main.py", line 70, in suggest
embed.set_footer(name=ctx.author, icon_url=ctx.author.avatar.url)
TypeError: set_footer() got an unexpected keyword argument 'name'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\bot.py", line 1182, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 904, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 194, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: set_footer() got an unexpected keyword argument 'name'
alr
oh I suppose I could save a couple lines with that
how do I parse a string by the symbol %%
why is this showing an error?
;-;
wrong server oops
remove the blank spaces
im using a cog lol
@torn sail
Ignoring exception in command suggest:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 185, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\youse\Downloads\Airline\DiscordBots\FlyAscent\Embed bot\main.py", line 70, in suggest
embed.embed.set_author(name=ctx.author, icon_url=ctx.author.avatar.url)
AttributeError: 'Embed' object has no attribute 'embed'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\bot.py", line 1182, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 904, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 194, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Embed' object has no attribute 'embed'
Show ur code
embed.set_author not embed.embed.set_author
ohhhhhh
^
@torn sail @slate swan tyvm
TabError: inconsistent use of tabs and spaces in indentation
try a help channel for this #❓|how-to-get-help
since it's not discord bot specific
feel free to ping me after claiming one
Yes
Refactoring is a good practice
Can learn a lot
Use a managed database provider
Not on repl.it
yo anyone knows wer to host discord bots
Slash command auto completion?
yes
by making it
what database do you wanna use?
Another build override, for slash commands localization :D
do you know SQL?
How can i make it so, when a user types Change, The discord channel changes it name to "Change"
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
await bot.db.commit()
oh ok
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 3 supplied
await cursor.execute("UPDATE levels SET xp = ? WHERE USER = ?", (xp, author.id, guild.id,))
someone?
U have 2 vars buy supplying 3
Well you have 2 ?, but provided 3 arguments
hmm
Is it possible to setup webhooks using bot?
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.
Changed in version 1.1: Added the `reason` keyword-only parameter.
Aha thanks for that....!!
technically it's one argument since it's a tuple
nvm
sqlite3.OperationalError: no such column: ctx.guild
should i change it to guild
or something else?
Also are you using sqlite or aiosqlite?
aio
Your error says sqlite3 but you're awaiting your statements
You should but it looks like you're using sqlite3
but i imported aiosqlite
so i have to remove await
No don't
Leave it I don't think it's a problem, just send how your code looks now
@bot.command(aliases = ['lvl', 'rank'])
async def level(ctx, member: nextcord.Member = None):
if member is None:
member = ctx.author
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND ctx.guild = ?", (member.id, ctx.guild.id,))
xp = await cursor.fetchone()
await cursor.execute("SELECT level FROM levels WHERE user = ? AND ctx.guild = ?", (member.id, ctx.guild.id,))
level = await cursor.fetchone()
if not xp or not level:
await cursor.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, member.id, ctx.guild.id,))
await bot.commit()
try:
xp = xp [0]
levels = levels [0]
except TypeError:
xp = 0
level = 0
user_data ={
"name": f"{member.name}#{member.discriminator}",
"xp": xp,
"level": level,
"next_level_xp": 100,
"percentage": xp,
}
Ah found the issue
Look here:
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND ctx.guild = ?", (member.id, ctx.guild.id,))
yes
You're looking for a column called ctx.guild
Not the actual guild ID, but the exact string
Change it to match your database, yes
in the whole code or in that line
Though storing a guild ID is not important for a leveling system
All you need is the user ID and XP they have
yes
Looks like you always have it in your 2nd one
Just make sure your not passing ctx.guild as the actual column heading
Since it's a string literal, it's not resolved to the guild ID
hmm
but rather it's kept as the actual string and looks for a column named "ctx.guild" exactly like that
so what should i do?
Make sure it matches up with your database
change every ctx.guild to guild?
👍
Sure should work
okie
Dudes been asking the same question 4 times in a row
XD
Well it's not all about "what should I do" or "what should I change it to" you should be logically thinking on what the problem is, possible solutions, and if it could or could not work
wth
Command raised an exception: NameError: name 'guild' is not defined
ctx.guild
if it was not sqlite , i would stand a chance
He didn't understand a word you said
but this out of my expertise
Well you took it too literally
You have changed all occurrences of ctx.guildwith guild
yes
The helper meant the ones that are inside the query strings
Like I mentioned it's not just a find and replace operation you need to think where it would be logical to use ctx.guild and where it would be logical to use just guild
IDk XD
aiosqlite and sqlite are the same thing, you just append await in front of most operations (a low level explanation of it)
now the place where u told to change, its now having a name eroor
technically same
"append await in front"

There's a lot more to it, but in many cases it can function as a thin wrapper around sqlite3
append means to put something at the end of a sentence/document, you just contradicted what you said
Oh crap

Then unshift if you're coming from JavaScript
when i changed guild to ctx.guild i get this
OperationalError: no such column: ctx.guild
if i change ctx.guild to guild i get this replied message
Like I said, it's not a "should I change everything to this" or "change everything to that", try to reason where it would be logical to change what and where
You won't learn anything from me just telling you what to change
we arent here to just tell you everything, you need to APPLY YOUR OWN brain too

ik
That's strong wording, but yes, my point exactly
but (i cant say excuse so imma leave)
uhhh
XD
Think on it a little bit and let us know if you need help on how to solve it
We don't mind telling you how to solve it, but we won't just tell you exactly what to do to fix it
imagine getting ignored off this 😔
Again, that's the same thing
ummmm
It's not all changing something
Your queries need to actually match up your database column names
Say you have 3 columns: X, Y, and Z, you can do a query like so:
SELECT X, Y FROM TABLE_NAME
guild = bot.guild ??
Why would bot have a single guild property?
hmmm
A bot can be in multiple guilds, so it doesn't make sense to have a single guild property
ik
It does, however, have a guilds property
?
I'm just saying your queries need to reference actual columns
"ctx.guild" is not a column name from what I can see
yes so
No
Well, but don't write that in your code, you need to replace it with guild in your query strings
Or you can just get rid of guilds from your database, you don't really need it
You just need 2 columns, user ID and xp
Now that might give rise to another problem of ctx.guild
ik so
yeah
I'm only suggesting a logical data model
it will show for all guilds
This person probably wants a per guild level system
Hm I see
It's totally fine then
Then yeah I suppose you'd need it
yes
call me ||idiot||
cursor.execute("SELECT userID, XP from LEVELS where guild = ? ORDER BY XP DESC", (ctx.guild))
something like that for fetching all users in a guild?
If it's like that then yeah you would need guild
i GOT IT
THANK U
'Member' object has no attribute 'avatar_url'
sed new error
oh ok
member.avatar.url
its .
roger that
Sorry if that felt like it took long to get help. I just want to make sure you learn something instead of being spoonfed, I hope you understand
The slate?
Really? Do you have the link to the build?
👋
Lmao idk wtf is even localization tbh. Is it like the language is changed? for slash commands
Just stuff like date and time formats I suppose
Prolly
np i also do the way you do things to people less knowledgeable than me
AttributeError: 'Bot' object has no attribute 'db'
new error tho
Yeah you need to actually assign db as a bot var somewhere, preferably on startup
bot = commands.Bot(...)
bot.db = ...
# commands here
bot.run(TOKEN)
something like this?
setattr(bot, "db", await aiosqlite.connect("level.db"))
😔 setattr
No need to use setattr
hmm
Dot notation invokes that
bot.db = ...
?
Keep in mind it has to be inside a coroutine
oh ok
2.0 supports the setup_hook coroutine
on ready?
await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.login "discord.Client.login") + [`connect()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.connect "discord.Client.connect").
I wouldn't
telling me?
yeah slash commadns are weird
I'm pretty sure it's still suspect to the downfalls of on_ready
umm
They made the setup_hook for a reason
what word could this conceivably be
LMAO
stretch hater?
I also thought the same but its a hangman game iirc
i cant even cheat to check as i dont have a way to do so
LMAO
XD
should be a single word
in englsih
This is where grep would come in handy
👀 Katte betrayed by their own bot
this is fucked up man
the bot has soft locked letter guesses meaning weve gone through every possible letter
variables doesnt help
They should
Uh
U can always print the words to console
i don tthink i can do that mid game
Yup u will have to restart the bot
i can just run the startgame commadn lol
Lol
You can always use a words API or smth
nope
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
it must work without variable for bot.db
i was wondering how do i @ an discord user using my bot?
so the bot prints out their @
im using a module that generates an english word
Mind showing the code where u r getting the word?
str(user)
!d discord.User.mention
property mention```
Returns a string that allows you to mention the given user.
idk which one u need
what library are you using for SQL?
that
aiosqlite
are you seriously gonna use this library for your hangman game 
idek what carboxyethyl is
Organic carbon compound
yes, just get good
i never said the bot was good
the game master can always manually start a new round
in theory
🤣
An idiot like me be like: Let's just forget hangman on discord and play some PC Games
Are more then 1 on_message events possible?
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
the function name can be anything, add the deco like this @listen("on_message")
Under @client.event ?
slight issue: it can generate hyphenated words
ill solve that later ™️
can someone help me in #bot-commands tryna make a python hangman game 
u can just see if "-" in word and if it is, then regen
yeah but thats more code than i wanna write at 11:30
ive been testing and iterating thsi hangman game for a few hours now
and im done for the night
Haha cool
this exists 
that wond get me bots
also not as fun
how do i add my discord bot to an VPS?
use their documentation
how do i @ a certain role using discord.py
!d discord.Role.mention
property mention```
Returns a string that allows you to mention a role.
i dont understand it
If you have a role object, just do .mention on it.
get a Role object and then use the mention property on it
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
role = guild.get_role(ID)
mention = role.mention
await ctx.send(f"Hey, everyone with this role: {mention}")
bot = Bot()
@bot.command()
async def mention_example(ctx):
role = bot.get_guild(guild_id).get_role(role_id)
await ctx.send(f'Mentioning....{role.mention}')
nvm am always late
Or instead of bot.get_guild(guild_id just do ctx.guild.
Error: NoneType has no attribute get_role
nice
Where is the docs for discord.TextChannel.history.flatten?
what vps yall suggest?
Do I need to remove duplicate code if I have different cogs for different versions of my gambling games?
idts that flatten is a thing in 2.0
and message has a history? huh?
For example, I read the url for my mongodb connection from a json file, and when I load the file to read the connection in each Cog file, it says I have duplicate code and should fix it
hello
you need a TextChannel object for the channel history
profile_picture = await load_image_async(str(member.avatar.url))
AttributeError: 'NoneType' object has no attribute 'url'
error
member.avatar_url
huh? can you show the code and the error?
It's not an error
Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
I just have duplicate code for reading my JSON file in every Cog
and Pycharm doesn't like that
Is it a bad thing? If so, how would I fix it?
I also have created my own checkFailures, and I have those duplicated in each Cog where I need them
huh? whats your discord version?
nextcord
code
oh then try doing
member.display_avatar.url
Im looking into gettign an VPS in order to host my bot for 24 hours, What VPS Do you suggest
data = json.load(file)
cluster = MongoClient(data['mongo_url'])
db = cluster['discordbot']
collection = db['users']```
I have this in 3 of my files
Because I connect to my DB using that connection in each file
And it doesn't like that I have duplicate code
you could make one function and use it everywhere
Im looking into gettign an VPS in order to host my bot for 24 hours, What VPS Do you suggest
dont spam
If you need to run your bot 24/7 (with no downtime), you should consider using a virtual private server (VPS).
This is a list of VPS services that are sufficient for running Discord bots.
https://www.scaleway.com/
Based in Europe.
https://www.digitalocean.com/
US-based.
Considered by many to be the gold standard.
Locations available across the world.
https://www.ovh.co.uk/
France and Canadian locations available.
https://www.time4vps.eu/
Seemingly based in Lithuania.
https://www.linode.com/
Cheap VPS.
https://www.vultr.com/
US-based, DigitalOcean-like.
https://galaxygate.net/
A reliable, affordable, and trusted host.
There are no reliable free options for VPS hosting. If you would rather not pay for a hosting service, you can consider self-hosting. Any modern hardware should be sufficient for running a bot. An old computer with a few GB of ram could be suitable, or a Raspberry Pi (any model, except perhaps one of the particularly less powerful ones).
noob question, but how would I fix the unresolved references?
dont use stuff before you assign them 
But I just put all that code in the function
and all the code after it is now confused
huh
Oh would I just make the variables global?
data = json.load(file)
cluster = MongoClient(data['mongo_url'])
db = cluster['discordbot']
collection = db['users']```
in this code, collection is used throughout the code. Once I put it in a function, I got errors every time it's used. Would I have to make it global?
Yeah, I feel like I remember global was a bad practice
I add return collection to the end, but I still get warnings that collection in the code has an unresolved reference
''' your file dir '''
Bot/
cogs/
example_cog.py
db/
connection.py
__init__.py
bot.py
.env
''' this should be your connection.py '''
import json
from pymongo import MongoClient
async def connect():
with open('./data.json', 'r') as file:
data = json.load(file)
cluster = MongoClient(data['mongo_url'])
db = cluster['discordbot']
return db['users']
''' this should be your __init__.py inside db folder '''
from connection import connect
''' this should be your cog inside cogs folder '''
from . import db
collectioon = await db.connect()
I have a json file with the url for it and I was just grabbing the url from there to connect
In your second block there, is that supposed to be return?
wdym
oh yeah sorry, typo
no worries
So for adding that db folder, would it be a new directory or a Python Package?
hm, pftt
Would it do that if I just had my first code pasted into every file?
What’s the best VPS for the discord bots as well there is a guide with the vps since I’m new to those
She told you above lol
no comments
I see. So just so I am understanding this, what Ashley was suggesting was that I had the function for connecting in its own file (connection.py) and then I import that into each cog?
And you're suggesting I just put that connection into my main file and use that function in the other files
yes that, but in the db.py, do this instead
import json
from pymongo import MongoClient
with open('./data.json', 'r') as file:
data = json.load(file)
cluster = MongoClient(data['mongo_url'])
async def connection():
db = cluster['discordbot']
return db['users']
this should only establish the connection once
i got netcup pretty cheap and good service for your money, highly customizable and friendly UI
Ok, Ill try that
Uh, docs doesn't say anything about 2.0
I meant discord.TextChannel.history.flatten
@slate swan does this mean the whole with open('./data.json', 'r') as file: data = json.load(file) cluster = MongoClient(data['mongo_url'])
should go in the __init__.py file?
She said in connection.py
That was originally in the function
But now it is not, does that change anything?
.flatten isn't a thing in dpy 2.0+ iirc
Hey! Can anyone tell me some way to get all the valid names for emojis?
!d discord.Client.emojis
property emojis```
The emojis that the connected client has.
ure on the stable one, go to latest
pretty sure 2.0+ isn't stable yet
Can you give me an example of how to use it?
bot.emojis
```returns a list of all emojis the bot has
That will return all the unicode emojis?
emoji objects iirc
Just emoji objects
Yeah so I can iterate through it and get the names. Let me try to see if that was what I was looking for.
Like [👍, ➡️, 🤷♂️]
use motor
has access to*
thats not an emoji object
What is use motor? lol
it's an asynchronous version of pymongo
!d discord.Guild.emojis
All emojis that the guild owns.
What would that change about my code?
every method that does something to your database needs to be awaited e.g py def main() -> None: col.find_one(...) needs to be ```py
async def main() -> None:
await col.find_one(...)
Is this just an optimizing thing? I would still have my problem at hand
its just the asynchronous version of pymongo, meaning, it wont block the rest of your code while interacting with the mongobase
So I should just import it and then put await in front of all of my interactions?
or can I completely replace pymongo?
Uhm, this is my requirements:
matplotlib==3.5.1
matplotlib-inline==0.1.3
mpmath==1.2.1
numpy==1.22.0
py==1.11.0
pymongo==4.0.1
requests==2.27.1
discord==1.7.3
discord.py==1.7.3
aiohttp==3.7.4
async-timeout==3.0.1
discordmongopy==0.3.0
motor==2.5.1
pymongo==4.0.1
``` Got no clue what to change
- don't use motor and pymongo together
- why do you need discordmongopy
hi kayle
Hi δεκριελ
how to know how much servers is your bot in(names too)
you need to become greek
@cosmic agate bot.guilds perhaps?
yes with the names too
!d discord.ext.commands.Bot.guilds
property guilds```
The guilds that the connected client is a member of.
Lmao
my dpy is a bit rusty
doesnt help , nothign there
len(bot.guilds)?
oh ok
Each guild object in bot.guilds should have a name attribute
oh boy
iterate through bot.guilds and just print guild.name
oh ok
names = "\n".join(guild.name for guild in bot.guilds)
so
Ok
names = "\n".join(guild.name for guild in bot.guilds)
@bot.command()
async def servers(ctx):
await ctx.send(names)
will this work?
That works!
hmm
No
Or add a @
@bot.command
done
Put the name thing inside the command
hmm ok
Else it won't update when the bot joins a new guild.
Is Ashley still here?
?
It wouldn't work anyway because the bot hasn't started so the cache is empty
Doesn't seem like it
its simpler




