#discord-bots
1 messages ยท Page 552 of 1
I'm not at home so i can't show you, i try to find them online, wait a second
it will only return one role
Yes you have to iterate through it
which site should i use to host my bot? (as in sites like heroku)
yes, but I dont want to print one role, I want to print the names of everyrole in the guild
???
how do i get a member's roles
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [โ@everyone](mailto:'%40everyone)โ role.
These roles are sorted by their position in the role hierarchy.
which site should i use to host my bot? (as in sites like heroku)
Any paid vps
@bot.command(pass_context=True)
@commands.has_role("Admin")
async def unmute(ctx, user: discord.Member):
role = discord.utils.find(lambda r: r.name == 'Member', ctx.message.guild.roles)
if role in user.roles:
await bot.say("{} is not muted".format(user))
else:
await bot.add_roles(user, role)
```py
What?
It was utils.find btw you have to use lambda
ctx.guild.roles
that returns a list
i need to access the names
and idk how to do that since roles doesn't have the name attribute
anyone able to help me fix a bump bot?
roles = [role.name for role in ctx.guild.roles]
Yes use this, role is equals to that list, so role.name is equals to role name and you can memtion it
no, roles doesn't have the name attribute?
im confused
What are you on? I think you need to learn a bit more python first.
Nah I'm following the docs? https://discordpy.readthedocs.io/en/master/api.html#discord.Member.roles here, roles doesn't have any attribute
i suggest trying this first before making assumptions roles = [role.name for role in ctx.guild.roles]
The role name.
hmm where in the docs can I find this
No where since it is just python
Bro just listen:
role = discord.utils.find(lambda r: r.name, ctx.guild.roles)
This returns you a list like the one you get from guild.roles
The name of the role.
So you just iterate through them and send the role
hm I see
But role is just the name of that list cuz is lambda r: r.name
!source
it dosn't return a list tho, it gives the first (only one) role
Cuz you have to iterate through guild.roles
you just just use a list comp for this
namelist = [r.name for r in guild.roles]
Yes you could do in that way too
roles = " ".join([r.name for r in ctx.guild.roles])
```How do I remove the everyone role and how can I mention the others?
Start from the second element in the list
why pass context
Index it
ty
It is not my code lol, take it from stack overflow
and you can do what @placid skiff said
I dont know what is wrong but it is not working, all this is it to set the invite for the servers bump ( its for a bump bot btw ) so If you know what wrong please state
# Broken
@bot.command()
@commands.has_permissions(manage_guild=True)
async def setinvite(ctx,*,desc):
file = open("data/invites.txt","r")
current = ast.literal_eval(file.read())
file.close()
try:
await ctx.send(f"Getting information for {desc} .")
invite = await bot.get_invite(desc)
print("Invite 1")
except:
await ctx.send("The invite is invalid. 1")
try:
if invite.guild == ctx.guild:
current[str(ctx.guild.id)] = desc
await ctx.send("Invite Set!")
file = open("data/invites.txt","w")
file.write(str(current))
file.close()
print("Invite 2")
else:
await ctx.send("The listed invite is not for your server.")
print("Invite 3")
except:
await ctx.send("The invite is invalid. 2")```
we won't know what's wrong
wdym?
using the remove() method?
The everyone role is always the first element in the list when you get the list of all roles
So if you start from the second element you will skip it
oh ok, do I use pop() or remove() in this case?
There is no need, use list slicing
!e
list[0,1,2,3,4]
print(a[1:])
you didn't specify a....
!e
list[0,1,2,3,4]
print(a[1:])
@sick birch :white_check_mark: Your eval job has completed with return code 0.
[2, 3, 4, 5]
Lol i'm drunk
there
Thanks
!e
a = ["hi", "lol"]
print(a[1:]
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | print(a[1:]
003 | ^
004 | SyntaxError: '(' was never closed
!e
a = ["hi", "lol"]
print(a[1:])
@slate swan :white_check_mark: Your eval job has completed with return code 0.
['lol']
y'all drunk lmao
there
oh ok, how come its not [0:]? isn't the first element in a list 0?
we don't want the first element remember
[0:] is the same thing as the actual list itself, it's not doing anything
That's what i said 10 min ago lol
name checks out
I started working this moring at 11 am and i take a pause just now lol
i think i know what it is
so
roles = " ".join([r.mention for r in ctx.guild.roles][1:])
removing the method u guys told me, now instead of mentioning the everyone role, it sends the ID
?
where do you do that
in an embed?
yes
you can't mention in the title
this is gonna panic when someone doesn't have any roles
i never did?
when a guild don't have any roles
but it always has everyone
Well you have to check if the guild.roles have at least one role if you don't know the guild
if it has everyone doing [1:] will freak out but i think that's more of an off-case
!e
a = ["hello"]
print(a[1:])
@slate swan :white_check_mark: Your eval job has completed with return code 0.
[]
One role except everyone
roles = " ".join([r.mention for r in ctx.guild.roles][1:])
if not roles:
roles = "None"
This will work?
By the way it just print None lol
exactly
Yes
oh cool, i was expecting it to error out
it shouldn't be an issue then
@slate swanthis will work?
mmm fair enough
I don't think an empty list activates the if not
It is not said cuz maybe discord py will throw NoneType object has no attribute mention
empty lists are falsy values
it's not even gonna do the loop once, so i doubt it
if len(list) == 0
then it's good
No no bro empty value will return false
Every empty value return False
you don't even need the if statement afterwards
if you try to iterate through an empty list it won't even run once
Hlo
If there is no roles it will be "" so it is falsy
!e
emptylist = []
for i in emptylist:
print(i)
@sick birch :warning: Your eval job has completed with return code 0.
[No output]
Can anyone help me adding token of bot in python
ye

bot.run("TOKEN HERE")
!e
emptylist = []
for i in emptylist:
print(i)
@pure plover :warning: Your eval job has completed with return code 0.
[No output]
Kk
!e print 666 on top
@pure plover :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print 666 on top
003 | ^^^^^^
004 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
then the if statement is already fine
!e help
@pure plover :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'help' is not defined
!d discord.Member.activity
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
How can I get just the name?
!e
i = ""
print(i)
@placid skiff :warning: Your eval job has completed with return code 0.
[No output]
of the role?
activity
i would assume activity.name but i'm guessing
pro tip, you can click on the embed title in !d and it will bring you to the docs
i am owner of bot ryzen it is is 75+ server and it anti nuke so intents are on i applied for verification also but unfortunately i close it intents and it is not enable now what Should i do?
showing every attribute
@slate swan
I have no idea
not quite understanding you
Hey @pure plover! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
@pure plover :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'bot' is not defined
i dont know actually
The name of the activity.
if i were you i'd look under the attributes section of discord.Activity
welp
oh I didn't know there was an activity class
๐ค
what does ctx.send_help this do? Is this literally what it says?
said again, good semantics
hmm so I have to do the same thing to activity as I did for roles huh?
Kk
exactly what it says
Nope, it's probably another function
oh
so, which one is correct
when you create a text channel using this method it returns the created channel object. so you can assign the returned object into a variable
channel = guild.create_text_channel(name="bruh")
or I can just make a quick function and test it out
it sends either the default help or a custom class if you have one
i assume it calls the send_bot_help() of bot.help_command
(assuming it's set)
Thank you very much for your kind attention.
it returns this <bound method Context.send_help of <discord.ext.commands.context.Context object at 0x7f6d357b5ac0>>
what is that ;-;
he's not wrong
it technically does return that
the location in memory may be different but that's beside the point
I still dont know how to get the activity name of a MEMBER
member.activity returns discord.Activity yes?
so you should be able to do member.activity.name
nope doesnt work
what error are you getting?
that discord.Member.activity has no attribute name
!d discord.Member.activity
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
that's odd, can we see your code?
hmm
returns discord.activity.Activity
embed.add_field(name="Activity:", value=f"{arg.activity.name}", inline=True)
!d discord.activity.Activity
class discord.Activity(**kwargs)```
Represents an activity in Discord.
This could be an activity such as streaming, playing, listening or watching.
For memory optimisation purposes, some activities are offered in slimmed down versions:
โข [`Game`](https://discordpy.readthedocs.io/en/master/api.html#discord.Game "discord.Game")
โข [`Streaming`](https://discordpy.readthedocs.io/en/master/api.html#discord.Streaming "discord.Streaming")
when you don't call it (in await expression)
what's arg?
i mean, it's type
a discord.User or a discord.Member
i see
it did send a help command!
but now I need to figure out how to send it for specific command
If you do it this way, you will get a sentence like the following
Is it possible to get only the ID part?
discord.Activity.name exists, but how do I get it from the member is my question
doesn't work
that's what i said but they said it doesn't work
what's the error
so now i'm confused
are you using the default help command? (subclassed)
ive said it multiple times now
iirc, yes
Just paste the error you get from your console so we can read what is the issue
Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
you can get the channel's id by the id attribute
The channel ID.
class MyNewHelp(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
emby = discord.Embed(description=page)
await destination.send(embed=emby)
bot.help_command = MyNewHelp()
``` I use this
member.activity should return an instance
member.activity != discord.Member.activity
so you can override send_command_help()
but how?
nah nvm I fixed it, the typehint for the arg was a little fucked
explains it
yup it works now
Nah you can do that, but you have to know what you are doing
override send_command_help()
My bot is a customized Bot class for example
i mostly mean the base discord models like discord.Member and such
and there is a good gist for subclassing default help command
ehhh, what?
Yes those are useless to work with the base class
https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96 this gist will definitely help you
ah yeah
Sorry to bother you again.
Can you tell me how to use the id attribute?
you can use it however you like, it's an integer
you can print it, send it over discord, store it, whatever
!remind 24h read with time
Sorry, you can't do that here!
if your textchannel object's name is channel then channel.id will give you the id for that channel
;-;
why is it looking like this? i want the photo at the right
@bot.command()
async def serverinfo(ctx):
guild = ctx.guild
a= len([m for m in ctx.guild.members if not m.bot])
b= len([r for r in ctx.guild.roles])
c= len([c for c in ctx.guild.text_channels])
d= len([d for d in ctx.guild.voice_channels])
e= len([e for e in ctx.guild.emojis])
f= len([f for f in ctx.guild.categories])
g= ctx.guild.mfa_level
h= "a"
if g == 0:
h = "No"
else:
h = "Yes"
embed = discord.Embed(colour=0x87CEEB)
embed.set_author(name=f"{guild.name} Information!", icon_url = guild.icon_url)
embed.set_image(url=guild.icon_url)
embed.add_field(name="Server Owner", value=f"{guild.owner}", inline=True)
embed.add_field(name="Server ID", value=f"{guild.id}", inline=True)
embed.add_field(name="Server Region", value=f"{guild.region}", inline=True)
embed.add_field(name="Categories", value=f, inline=True)
embed.add_field(name="Text channels", value=c, inline=True)
embed.add_field(name="Voice channels", value=d, inline=True)
embed.add_field(name="Rules channel", value=f"{guild.rules_channel}", inline=True)
embed.add_field(name="AFK channel", value=f"{guild.afk_channel}", inline=True)
embed.add_field(name="Updates channel", value=f"{guild.public_updates_channel}", inline=True)
embed.add_field(name="Members", value=a, inline=True)
embed.add_field(name="Roles", value=b, inline=True)
embed.add_field(name="Created at", value=f"{guild.created_at} **UTC Time**", inline=True)
embed.add_field(name="Boosts", value=f"{guild.premium_subscription_count}", inline=True)
embed.add_field(name="Emojis", value=e, inline=True)
embed.add_field(name="Emojis limit", value=f"{guild.emoji_limit}", inline=True)
embed.add_field(name="Verification Level", value=f"{guild.verification_level}", inline=True)
embed.add_field(name="2FA", value=h, inline=True)
await ctx.send(embed=embed)```
Thank you very much! It's all fixed! I can't thank you enough!
np
use set_thumbnail method for it
okk
!d discord.Embed.set_thumbnail
set_thumbnail(*, url)```
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the thumbnail.
thanks!!!!!!!
Remember that the thumbnail take a lot of spaces so on phone the field inlined will mess up a lot
in my phone its everything with inline
so its a flooding machine XD
inline thing doesn't work on mobile client
They actually do lol
do u like this?
i guess not
Yes bro i tried them
They're a lot ugly tho ๐
looks cool on desktop , but eww on mobile
I am trying to make a bot by watching video on YouTube but IDK what mistake I made, it is not working and I have 0 idea about programming language so please help me someone
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Start by learning python first
As it says, your token is wrong
ok how much time it will take?
Learn python first its better
Depends on how fast you learn
Pretty sure it's not otherwise you wouldn't have that error, copy paste it again
Depends on everything patience time how quick you learn
And make sure you don't have any typos to it
First learn programming lenguage
I suggest you to start with C to get a good basic, you can just learn directly with python but you will be confused with a lot of things
Then learn python, at least you should have an idea of object oriented programming, then you can start coding with bot
Code?
Then idk, are you simply putting your token in the .run or are you getting it from a .env
k ma'am
I mean its good but its better to stick with a programming language know allot about it and then when your skilled you learn another one
Im a guy bruv
i know its not the best way
You didnโt define the TOKEN var.
You're not actually passing "TOKEN" when running right?
what is C?
It's a string
Programming language
sorry man.
Idc lmao
?
?
i just deleted it out bc i dont want to share it
C is even more confusing so i don't recommend it until you pick something easier to learn like python, + he might not even ever need C
@river hollow if you have your bot's token stored in env variables then load it in your script first
but in my code have it
would you mind if I dm you?
Then idk
i dont have this
Then you did run you variable thats a random string of letters and not actually TOKEN
Go for it
Yes oc
When i started i learned C, i studied till i learned memory management then i moved to other languages
The C gives you a good knowledge so even if you code on other language you will have a good idea on what you are doing, I personally think it's essential cuz if you start with python which is simple for beginners but when you move to use external package it will be pretty caothic if you don't know some things
Then pass the token directly
i copyed the token and just pasted it in the .run
In .run
Hey @river hollow! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
bruh
Everybody doesnt learn as equal to you python is a very good beginner friendly language i would recommend learning c after python but its not necessary
It is not confusing, it is hard cuz you don't have a lot of shortcuts that other programming languages have, so you have to create your own way to do some things
Still you don't know if he's gonna ever need it, maybe he just wants a discord bot, you don't need to go out of your way and learn C first before python
He could make the bot in C :D
That would take a lot more time rather than doing it in python ๐
Yes bro but the fact is, I try to explain it simple
C will make you use your brain to do certain things, this will train your mind so you will solve problems instead of tryin to find shortcuts
Yeah and it would blow up from the slightest mistake
Why is it sending the message so many times?
@bot.command()
@commands.has_permissions(manage_guild=True)
async def setchannel(ctx,*,desc,given_name=None):
file = open("data/channels.txt","r")
current = ast.literal_eval(file.read())
file.close()
for channel in ctx.guild.channels:
if channel.name == given_name:
await ctx.send("Please mention a channel next time.")
else:
wanted_channel_id = channel.id
current[str(ctx.guild.id)] = wanted_channel_id
await ctx.send("Bump Channel Set!")
file = open("data/channels.txt","w")
file.write(str(current))
file.close()
print(wanted_channel_id)```
There is a C discord library though https://github.com/cee-studio/orca
It's quite good
I still find it unnecessary for a mere discord bot
Because you're looping and sending the message each time it loops
what should I change to not loop?
Remove the for loop
ok
That's really basic python
Programming isn't always write code following some path
Most of the time programming is create a problem, solve it and then process it
Python will give you the necessary so you will not have to solve directly the problem
But when you have to do complicated things, like doing a bot, you have to know how to solve some algorithm problems
What the fuck is this code
lmao
Ngl i thought of that too ๐
Not really, if it's a basic or simple bot you really don't
Bad I do know
I think that if i wouldn't learnt C i will be a lot in trouble with the bot i'm creating
Like why are you using ast.literal_eval?
That doesn't apply to everyone
For example, I've never had any knowledge of any other language but python and got my bot some dope advanced and complex commands
Mmm most of the things C teachs you are irrelevant for discord bots
^
But in general it is good practice
In therms of coding yes
But in therms of algorithms and problem solving no
Teachs you the way to do things without relying on anything
Exactly
Learning a language that you might never need doesn't hurt, but if you're not gonna get that far into programming nor plan on keep going and just doing it for the moment then it's pretty useless
Yeah but with what most people do they don't even need to solve any problems as it has all been nicely done for them already
Lol maybe is just that i'm not one of those people who creates something that already exists ๐
Your bot seems pretty basic you also do some odd things
Like what is this
Just use getattr D:
Well not exactly
I'm just sharing modified code so they will look more common and find simple ways to solve problem ๐๐
As i said i've C mentality so i'll solve problems in my own way ๐๐
Btw the code is pretty old now, i've not uploaded it yet ๐
I will try btw, i'm just not used so i prefer doing it like this
For python the C mentality isn't the best approach
Till now it worked fine
It works it just isn't the best
@bot.command()
async def serverinfo(ctx):
guild = ctx.guild
a= len([m for m in ctx.guild.members if not m.bot])
b= len([r for r in ctx.guild.roles])
c= len([c for c in ctx.guild.text_channels])
d= len([d for d in ctx.guild.voice_channels])
e= len([e for e in ctx.guild.emojis])
f= len([f for f in ctx.guild.categories])
g= ctx.guild.mfa_level
h= "a"
if g == 0:
h = "No"
else:
h = "Yes"
i= round(ctx.guild.created_at)
embed = discord.Embed(colour=0x87CEEB)
embed.set_author(name=f"{guild.name} Information!", icon_url = guild.icon_url)
embed.set_thumbnail(url=guild.icon_url)
embed.add_field(name="Server Owner", value=f"{guild.owner}", inline=True)
embed.add_field(name="Server ID", value=f"{guild.id}", inline=True)
embed.add_field(name="Server Region", value=f"{guild.region}", inline=True)
embed.add_field(name="Categories", value=f, inline=True)
embed.add_field(name="Text channels", value=c, inline=True)
embed.add_field(name="Voice channels", value=d, inline=True)
embed.add_field(name="Rules channel", value=f"{guild.rules_channel}", inline=True)
embed.add_field(name="AFK channel", value=f"{guild.afk_channel}", inline=True)
embed.add_field(name="Updates channel", value=f"{guild.public_updates_channel}", inline=True)
embed.add_field(name="Members", value=a, inline=True)
embed.add_field(name="Roles", value=b, inline=True)
embed.add_field(name="Created at", value=i + "**UTC Time**", inline=True)
embed.add_field(name="Boosts", value=f"{guild.premium_subscription_count}", inline=True)
embed.add_field(name="Emojis", value=e, inline=True)
embed.add_field(name="Emojis limit", value=f"{guild.emoji_limit}", inline=True)
embed.add_field(name="Verification Level", value=f"{guild.verification_level}", inline=True)
embed.add_field(name="2FA", value=h, inline=True)
await ctx.send(embed=embed) ```i want to round the created at
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/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: TypeError: type datetime.datetime doesn't define __round__ method
Good to know
I like to learn and i'm also a self-learner
So in future it will be certain better
!d round
round(number[, ndigits])```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.
For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.
For a general Python object `number`, `round` delegates to `number.__round__`.
dose anyone have a reason why this is not working
What error it throw?
By yhe way there is no need, try this:
async def on_member_join(member)
await ctx.member.send(message)
Why are you using list comp on a list to create a list to count the list again?
isn't len(ctx.guild.roles) good enough?
ah thx
idk, but that is not the error
This is -> i= round(ctx.guild.created_at)
Why are you trying to round a datetime?
because its ugly xd
ik, how i can fix it
What do you want it to be instead?
ctx is undefined
without decimals
!d datetime.datetime.strftime
datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
Sorry is just member.send
that doesnt tell me how to round it
It's literally the function of how to round it.
Did you click on the link?
created = ctx.guild.created_at.replace(microsecond=0)
This will still have decimals and please don't spoonfeed
How to get a member's custom status and about me?
!e ```py
from datetime import datetime
print(datetime.now())
print(datetime.now().replace(microsecond=0))
@bright palm :white_check_mark: Your eval job has completed with return code 0.
001 | 2021-10-22 16:15:39.989997
002 | 2021-10-22 16:15:39
Well time to go to the js server
How can i host my bot for free?
replt
hello I'm a python beginner and i'm developping a discord bot buit i have a problem : I want my bot to send a message every day on a fixed hour and i did not find a way to achieve it despite my researchs on stack overflow. can you please help me ?
is replit hosting?
where? doesnt workpy @bot.command() async def serverinfo(ctx): guild = ctx.guild a= len([m for m in ctx.guild.members if not m.bot]) b= len([r for r in ctx.guild.roles]) c= len([c for c in ctx.guild.text_channels]) d= len([d for d in ctx.guild.voice_channels]) e= len([e for e in ctx.guild.emojis]) f= len([f for f in ctx.guild.categories]) g= ctx.guild.mfa_level h= "a" if g == 0: h = "No" else: h = "Yes" created = ctx.guild.created_at.replace(microsecond=0) embed = discord.Embed(colour=0x87CEEB) embed.set_author(name=f"{guild.name} Information!", icon_url = guild.icon_url) embed.set_thumbnail(url=guild.icon_url) embed.add_field(name="Server Owner", value=f"{guild.owner}", inline=True) embed.add_field(name="Server ID", value=f"{guild.id}", inline=True) embed.add_field(name="Server Region", value=f"{guild.region}", inline=True) embed.add_field(name="Categories", value=f, inline=True) embed.add_field(name="Text channels", value=c, inline=True) embed.add_field(name="Voice channels", value=d, inline=True) embed.add_field(name="Rules channel", value=f"{guild.rules_channel}", inline=True) embed.add_field(name="AFK channel", value=f"{guild.afk_channel}", inline=True) embed.add_field(name="Updates channel", value=f"{guild.public_updates_channel}", inline=True) embed.add_field(name="Members", value=a, inline=True) embed.add_field(name="Roles", value=b, inline=True) embed.add_field(name="Created at", value=f"{ctx.guild.created_at} **UTC Time**", inline=True) embed.add_field(name="Boosts", value=f"{guild.premium_subscription_count}", inline=True) embed.add_field(name="Emojis", value=e, inline=True) embed.add_field(name="Emojis limit", value=f"{guild.emoji_limit}", inline=True) embed.add_field(name="Verification Level", value=f"{guild.verification_level}", inline=True) embed.add_field(name="2FA", value=h, inline=True) await ctx.send(embed=embed)
uptimerobot but its illegal xd
Ah
.-.
i didnt understand anything ? is there a simple function which checks the hour of the computer ?
Ok so use datetime to get the current hour and if the hour is your expected hour....send the message
Another thing...if you put it in a while loop to check the hour every certain duration like 20 sec, make sure your bot doesnt message thousands of time as an hour stays for 60m.
I suck at explaining. Pardon
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/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: TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'str' @bright palm
embed.add_field(name="Created at", value= created + "**UTC Time**", inline=True) did this
You can supply a time argument to the task to specify the time it should run at
Make the datetime a string first?
oh yes
@slim whale @slim whale
@bright palm
Plss tell
๐ฅบ๐ฅบ
@bot.event
async def on_ready():
command_prefix="!"
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.listening,
name=f"{command_prefix}help"))```this is playing
No
i dont need to have a xhile function, do I ? because i use async
@bot.event
async def on_ready():
command_prefix="!"
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.listening,
name=f"{command_prefix}help"))
This?
Don't do this just use https://discordpy.readthedocs.io/en/master/ext/tasks/index.html
@pure plover
await bot.change_presence(activity=discord.Game(name="a game"))
but i didnt understand
yes
Me too
im gonna test your advice
@slim whale activity
Perhaps you should learn some more about python
Lol
bRUH
Haha
โ
how can I count the voice time that the users have done?
get the datetime they join the VC and the datetime they leave and find the difference, store that in a Database?
@commands.Cog.listener()
async def on_message(self, message: disnake.Message):
guild = self.bot.get_guild(880030618275155998)
owner = guild.get_role(884679735366533151)
if len(message.mentions) > 5:
# if owner in message.author.roles:
# print(f"Owner mentioned {message.mentions} people.")
# return
await message.delete()
await message.channel.send(
f"Too many mentions! {message.author.mention}", delete_after=7
)
``` no errors, but why does this not work?
somebody who can help me with a piece of code made in Discord? Might be the easiest for you! ๐ pm if possible?
what did you do in discord kayle
mention 10 people in a message
no dm, send it here
primarily me
maybe set an else to the if statement with something
ohhhh
maybe that returned false
i figured out why
if you pinged yourself
it doesn't trigger
BUT if you pinged 5 other people then it'll work
hm
How come the top part of the code gets disabled (the client.command)s. When I add the client.event
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
on_message stops other commands from working
doesn't say anything about that
you have to add client.process_commands(message) as the last line in the on_message
Then what do I do?
change @bot.event to @bot.listen()
that works too
above on_message
so client.listen()?
i find using listeners easier but use client.event if you want
yes
Let me try!
It says command doesnt exist. the !add command.
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "add" is not found
Code?
can we see your code for that command?
you should probably
make a command, not an event for that type of thing
iirc on_message doesn't receive args but im not sure
Then I have to change it completely.. so it would be better if it could just work.
you should use the commands extension
^
?
the commands extension lets you have multiple arguments in a command
like what you did earlier
then change it, there's no reason to be not using the commands extension
you're just gonna keep running into more and more issues like this
better switch now and save yourself the headache down the line
But I don't know how I would change it. I tried, but I hit a wall everytime I try change it to a command.
it's like making a function
perhaps you haven't read the documentation yet
but in discord
it has excellent command examples
^ or just read the examples folder
@bot.command()
async def echo(ctx, arg1):
await ctx.send(arg1)
very simple echo function
yes
Would the client.process_commands(message) maybe work?
you can add more parameters to it
it will but it won't work for your current code
I know how to make a bot.command function, but with the current code and what I want it to do, it gives tons of errors.
like what?
yeah you already have commands in your code
i'm looking at the pastebin one
why not just make more of that
Robin J, as you can see the client.event one is for a google sheet api
So thats why with command I would have issues doing what im doing.
i don't see why you would have issues with that
you can still interact with the API from within commands
nothing is limiting you from doing so
Let me show you errors I get.
do
you mean like this?
Yep!
```
stuff
```
Traceback (most recent call last):
File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Sebastian\Desktop\DiscordBot\bot.py", line 92, in add
if message.content.startswith('!add '):
AttributeError: 'Context' object has no attribute 'content'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python310\lib\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: AttributeError: 'Context' object has no attribute 'content'
So what do I do?
use the context object rather than the message
ctx.mesage.content
ur not supposed to have ctx in an event except some events
oh
So I made it? message.context.startswith ?
no the issue here is they're doing startswith inside of a function
ok
add ctx at first
why not just make a command wtf
Yup
yeah
just get rid of all your startswith and use commands
Wait...
its this easy
async def function(ctx, first, second, third, fourth):
```??
@slate island you using Client()?
exactly
he isnt
Ohh
async def add(ctx):
if message.author == client.user:
return
# Command to insert data to excel
if ctx.message.content.startswith('!add '):
SPREADSHEET_ID = 'idhere' # Add ID here
RANGE_NAME = 'A1'
FIELDS = 2 # Amount of fields/cells
# Restrict the command to a role
# Change REQUIREDROLE to a role id or None
REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(message.author.roles, id=int(REQUIREDROLE)) is None:
await message.channel.send('You don\'t have the required role!')
return
# Code
msg = message.content[3:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:
# Add
print(message.created_at)
DATA = [message.author.name] + [str(message.author.id)] + [str(message.created_at)] + result
sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
await message.channel.send('Your data has been successfully submitted!')
else:
# Needs more/less fields
await message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))```
they're using commands.Bot, but named it client
This is what I have so far.
I had a heart attack lmao
you're gonna get an error there
message isn't a variable
the 3rd line
use ctx.message instead
also why do you need startswith if it's inside the command
is if REQUIREDROLE is not None and discord.utils.get(message.author.roles, id=int(REQUIREDROLE)) is None: even valid syntax?
you're effectively checking if the message contents starts with "!add" twice
So everywhere in the code it says message.somethinghere
has to be: ctx.message.somethinghere
correct
Let me try.
how do i get the invite code and the inviter in an on_member_join event ?
why this not work when user isn't on the server?
there's no native way to do it so you'll have to cross reference the audit logs
error?
store the the person who created the invite in a db > check if the user joined from that invite
i don't have
error handler?
the id/tag isn't global + your bot cant fetch the user
how do i get the inviter which the person who join use ?
how i can fix it?
i dont know
i dont know???
get the invites and their uses before someone joins, after someone joins check which invite increased by one
then you know which invite they used to join
Doesn't work. Nothing happens. No errors either.
not helpful
async def add(ctx):
if ctx.message.author == client.user:
return
# Command to insert data to excel
SPREADSHEET_ID = 'idhere' # Add ID here
RANGE_NAME = 'A1'
FIELDS = 2 # Amount of fields/cells
# Restrict the command to a role
# Change REQUIREDROLE to a role id or None
REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
await ctx.message.channel.send('You don\'t have the required role!')
return
# Code
msg = ctx.message.content[3:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:
# Add
print(ctx.message.created_at)
DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
await ctx.message.channel.send('Your data has been successfully submitted!')
else:
# Needs more/less fields
await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))
zero error
then it's working like you made it
btw you can get rid of lines 3-4
ah you know why
lines 3 and 4?
everything afterwards is indented
so the whole code will only run if you send the command
but why this not ban user which isn't on the server?
which you never will
Sooo?
i assume it's because the bot can't "see" the user, so it doesn't know what to do
fix your indent, and remove the part where it checks if the bot is the one sending the message
So just remove line 3 and 4?
and fix your indents, yes
which indents?
everything in the command is indented into the if block
so everything only runs if ctx.message.author == client.user
i'm talking about this
what i should to in do the bot can see the user?
actually you should be getting unreachable code error
Yeah, but what lines for example. I just removed line 3 and 4.
please don't use ableist language here
the bot has to either share a server or be in a group chat with them
still have to fix your indent
Can you give a piece of a code that is indent in the code that I have to change?
you see where it says # Command to insert data to excel
deindent starting from there to the end of the command
I don't see the indents you are talking about. Sorry. :S
Because it seems to work fine now.
After I removed line 3 and 4.
Anything I have to be aware of? Because it seems to work sir.
so how i can do the bot not must be in a the same group chat with user or server?
Because you are using discord.Member and not discord.User.
now it at all not work
discord.User
My bad, it's a capital U. My keyboard lagged.
hii
Show your full code?
Use await ctx.guild.ban(user, reason=reason).
And also you can do member.mention instead of BannedUser = f"<@{member}>".
HII
!d discord.User.mention
property mention: str```
Returns a string that allows you to mention the given user.
still :/
Still what?
still not work
it can't convert to a discord.User if it can't see the user
that would raise a BadArgument error, but the converter is able to make an API call afaik so it will always work as long as the user exists
any error
Do you have any error handlers?
what is it?
i see, that makes sense as the converter is actually async
Ah, can you please put your code inside a try...except and raise the exception?
that wouldn't bypass any error handlers, you would need to print the error/print_exc
Well, instead of making a whole error handler, they want to just know what's wrong with this command.
@sick birch the code works when I removed line 3 and 4. How come it works when I didnโt change the indents?
most people will have their error handler in a separate cog, and unloading that cog would do the trick
I don't think they know how to use cogs.
yes, i'm still beginner so thats why i ask you for help
how i can raise exception?
except Exception as e: raise e
What's the use of a try block if you are only re-raising the same exception?
I have a question if there is any other way to check the permissions than @has_permission(permission=True)?
why
Member.permissions_in
TypeError: Cannot read property '1' of null
at Object.<anonymous> (/root/bot/heroku/app.js:7:113)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
const version = new RegExp("VERSION.{0,}=.{0,}'(.*)'").exec(fs.readFileSync(path.join(__dirname, '/../bot.py')))[1] // Get DiscordGSM verison from bot.py
I can't figure out why this is happening can you help me
this is javascript not python, you should ask in the js server
Ah sorry
in this line code has been stopped without raising any exception
Hey @half tide!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
https://paste.pythondiscord.com/ejequbabuk.py
inter response errors out
u can only respond to an interaction
once
we do it mupltiple times
in def gbanslash
read main.py -slash-commands branch
commit a change
u can test on ur own bot if necessary
activity_type = ""
try:
if arg.activity.type == "ActivityType.watching":
activity_type = "Watching "
elif arg.activity.type == "ActivityType.listening":
activity_type = "Listening "
elif arg.activity.type == "ActivityType.playing":
activity_type = "Playing "
elif arg.activity.type == "ActivityType.streaming":
activity_type = "Streaming "
elif arg.activity.type == "ActivityType.custom":
activity_type = "Custom "
elif arg.activity.type == "ActivityType.competing":
activity_type = "Competing"
except AttributeError as e:
print(e)
activity_type = ""
embed.add_field(name="Activity:", value=f"{activity_type}{arg.activity.name}", inline=True)
Hi, this is a info command, so when I do -info @mention it's going to send an embed with the mentioned users information. arg is either a discord.Member or discord.User. I'm trying to get the name of the activity type, but when I run the command on someone who has a activity, it sends only the arg.activity.name and not the type, which means that except is ran no matter what, and if the user doesn't have an activity, I get this following error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'name'
Traceback:
embed.add_field(name="Activity:", value=f"{activity_type}{arg.activity.name}", inline=True)
AttributeError: 'NoneType' object has no attribute 'name'
I've tried few ways to solve this but it doesn't work, any1 who could help me with this?
arg.activity is None
Yes I know that
then it should be pretty easy to fix no?
I have this, How do I make it so it deletes the 7 day old logs (ping me)
I said I tried, but I couldn't fix this, otherwise why would I ask for help? You need to understand this, I've seen u a few times trying to "help" but what you're really doing @hasty iron is making people regret asking because YOU expect us (newbies) to know every thing. Keep it nice instead and help, or if you don't want to help then shut up and move on
the library doesnโt expect you (newbies) to use it
it expects you to have some knowledge
and the fix requires a single if statement
i donโt know if thatโs hard or not
Oh really, so newbies shouldn't learn? Because that's how everyone starts right? You're logic is that if you don't know, don't do it. Right, but what if I try my best? And if I can't make it, I ask for help, this is what this channel is for. You're not welcoming people that's new to this library which literally is against the #code-of-conduct
Anyways, I'll ask in another server, ty tho
what? newbies shouldnโt learn?
youโre literally avoiding the whole point
to use discord.py you need knowledge and you apparently donโt have it
I don't have it because I couldn't find a solution to my issue? This is the first time I ran to this issue how am I supposed to know? This is the first time I coded a discord bot? What you have been saying to me the whole day, even when I asked for help before, is questioning my skill? I told you I'm new, all I'm trying is to get help
dude
Well, you should help yourself at the start.
Which I did
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
and as i said, this requires a literal single if statement
You didn't help yourself, because you haven't learnt Python before jumping into a higher level than newbie level library.
I literally took a basic python course in school, I'm completely new to this library and I'm asking for help wtf?
wow and you still donโt get the point
So what you're saying is basic python isn't enough for discord.py?
yes it isnโt
async def add(ctx):
# Command to insert data to excel
SPREADSHEET_ID = 'idhere' # Add ID here
RANGE_NAME = 'A1'
FIELDS = 2 # Amount of fields/cells
# Restrict the command to a role
# Change REQUIREDROLE to a role id or None
REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
await ctx.message.channel.send('You don\'t have the required role!')
return
# Code
msg = ctx.message.content[3:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:
# Add
print(ctx.message.created_at)
DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
await ctx.message.channel.send('Your data has been successfully submitted!')
else:
# Needs more/less fields
await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))```
How come this piece of code
when i type !add test test
Discord.py is an intermediate library, not basic.
it adds into the spreedsheet d test test
it adds a d into field 1? Where is the d from?
You can restrict the command to a role just by using a simple decorator. @commands.has_role(roleID).
I know, but it shouldnt only for certain situations.. so thats why I left it in and put none on it atm.
But into the spreedsheet when i type !add test test
it adds into field 1: d test and field 2: test
Where does the d come from?
I don't understand this logic, how do you guys expect someone to learn the library if they don't try? They will fail somewhere and I failed here, and I need help and you don't provide it because I have basic python knowledge and not intermediate? There is literally something I don't know how to fix, and this happens to everyone even if you're pro in pything
right if statements are related to the discord.py lib only
You know why @dapper cobalt ?
What do you save in the spreedsheet? Which variable?
When I type !add test, test
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.
msg = ctx.message.content.replace("add", "") try that.
It takes the d at the end of 'add'.
Should i add it or change it with something?
or you can strip it too
Index starts from 0 and not 1.
You talking to me?
No, I'm talking to my cat, his name is Soly.
lol
Change it to msg = ctx.message.content.replace("add", "").
Let me try. ๐
He said hi back whilst eating my headphones.
It kinda worked KeyError.
now it just adds the !
So when i type !add hey, hey it says:
field 1: ! hey
field 2: hey
Fixed it!
Thanks โค๏ธ
nice
https://paste.pythondiscord.com/ejequbabuk.py
inter response errors out
u can only respond to an interaction
once
we do it mupltiple times
in def gbanslash
read main.py -slash-commands branch
commit a change
u can test on ur own bot if necessary
@hasty iron
Haha, you can call me Scoopy. And I'm glad you figured it out.
Yeah, KeyError is my nickname here, check my username.
You can tell us what's the problem instead of just showing us your code.
Sorry heres one:
inter response errors out
u can only respond to an interaction
scoopy I love your website
i hate the kids in dpy, he said i was a skid because of my about me
as soon as i called him a skid he got butt hurt and made a mod ban me
lol
Is anyone aware of a public fork of discord py that is being actively updated and has interactions implemented?
i saw the entire thing and thatโs not what happened, anyways you shouldnโt bring other serverโs shit here
forks are allowed
there are mad forks of discordpy
well there are no good/decent ones, but the more popular ones are pycord and disnake
ah..
disnake? never hurd of it
And I love you. 
If you have knowledge of the API you can also just impl interactions yourself,
!pypi disnake
yeah,, thats what Im going to end up doing
huh this looks eerily similar to dpy
if you hate the dpy kids why are you here?
not what i meant
i meant the kids that assume your a skid because od your about me on discord.com
because it's #discord-bots and not #discord-py?
disnake was made by ppl who made dislash which was a popular 3rd party lib implementing slash n such in d.py
I'd wait before fully switching over 2 a fork personally
Do like me, switch language
I already switched language when it started to get an update every century
i donโt think switching a language because of discord bots is worth it
How to make a change that will represent the guild?
elaborate
How to make sure that if a person does not change the prefix for the bot, then use the standard prefix, and if changed the custom one
I love that custom_prefix variable
its spelt default
how i can do it ? how to remove the line? like in the picture? on python
what line?
maybe set the color to the embed color
the embed line?
OMG bro i love you thank you!!!
https://paste.pythondiscord.com/noyojexutu.rb
AttributeError: 'NoneType' object has no attribute 'id' | why is self.bot a none type
self.bot isn't the nonetype, self.bot.user is the nonetype
i dont know why it is nonetype at all, and im just gonna throw this out there - maybe bot isn't ready?
finish yours fast
api wrapper
Do you guys know how to translate html color into python, that is, I have the color 2f3136 and when I insert it into embed, an error appears SyntaxError: invalid syntax
hope you're using motor and not pymongo ๐๏ธ ๐๏ธ
you're doing color=?
thank you bro!
what you need to do is use the on_guild_join event. Whenever your bot joins a guild, open a database query and add ! to the prefix field associated with that guild.
This way, every guild your bot joins will already have that field filled in, and if they've set a custom prefix it'll ofc hold a diff value.
okay, thanks
Can someone give me the right format for a commands.Cog.listener()? I totally forgot what the correct arguments for it are, and I don't have any examples on hand in my code.
@commands.Cog.listener()
async def on_message(message): # <- What else here?
...
await bot.process_commands(message)
Currently gets TypeError: on_message() takes 1 positional argument but 2 were given
self, message
In the parameters, add self
make sure you have a backup inside get_prefix as well if you go that route. If your bot joins a server while the bot is offline, the on_guild_event won't run. So in the event that a guild is not found in the db, you can add it within get_prefix
Does this make sense? IDK, but that's how I do it
who r u
Caeden, who are you?
your idol's teacher
hey! Anyone here familiar with discord buttons?
Bro, I found this:
2021-10-22 13:48:46,243:INFO:nextcord.gateway: Websocket closed with 1000, cannot reconnect.
2021-10-22 13:48:46,243:ERROR:nextcord.client: Attempting a reconnect in 470.44s
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/nextcord/client.py", line 515, in connect
await self.ws.poll_event()
File "/home/container/.local/lib/python3.9/site-packages/nextcord/gateway.py", line 585, in poll_event
raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
nextcord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
code 1000 is an unknown error
so it just lost connection for a bit
and as you can see at the top it says attempting reconnect in 470 seconds hence why you see it reconnect after a while
yup
but yeah it's an unknown error so idk how to solve it
you can ask discord if they have more insight, but i doubt it
works fine for me
it lets me login i do the captcha and then takes me back to login
๐ค
disable your adblocker
i'm on mobile
Doesn't prove anything
I have ad blocker on mobile 
@avatar.error
async def avatar(ctx, error, member : discord.Member = None):
if isinstance( error, discord.ext.commands.errors.MemberNotFound ):
memberavatar = member.avatar_url
emb = discord.Embed(color=0x2f3136)
emb.set_image(url = memberavatar)
emb.set_author(name = f"{member.name}", icon_url = memberavatar)
emb.timestamp = datetime.utcnow()
await ctx.send(embed = emb)```help?
error:
`discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'avatar_url'`
If the member is not found, why do you try to get it's avatar

its an error handler anyways
...
And yeah, error handlers don't take custom parameters
thank you
@avatar.error
async def avatar(ctx, error, member : discord.Member = None):
if isinstance( error, discord.ext.commands.errors.MemberNotFound ):
emb = discord.Embed(color=0x2f3136)
emb.set_author(name = f"s", icon_url=member.avatar_url)
emb.timestamp = datetime.utcnow()
await ctx.send(embed = emb)```
`discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'avatar_url'`
help?
what?
...
You're kind of checking if it's none and if it's none then you send stuff
I want the bot to show the author's avatar_url
And error handlers don't take any parameter you wish
So I'm doing it wrong?
You should use @commands.command for sending the answer to your command and use @avatar.error to check for possible errors
Use a normal @commands.command decorator
What you're doing now is basically only send the avatar when the member is not found, which makes no sense at all and obviously throws a NoneType error
so how do I get the bot to show the author's avatar.url?
what i need use?
i need use embed.add_field?
embed.set_image
do u have member intents
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
can't find any proper examples of code in the docs of discord.py
of creating a thread
for a message, as I'm trying to create my own modmail bot
could someone send me some code on just the basics of creating a thread when a command is called?
so like, I want the bot to send the actual message to the moderators or people with mod+ perms in my server, which I don't understand how I can do.
!d help
help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
ok
How to combine two lists of strings?
how do you make your bot dm people
!d discord.Message.create_thread
await create_thread(*, name, auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a public thread from this message.
You must have [`create_public_threads`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads") in order to create a public thread from a message.
The channel this message belongs in must be a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel").
New in version 2.0.
list1 + list2
.send on the member
ah okay, @slate swan is there also a method to reply to a thread? I want a moderator to be able to respond to a thread that a person has created.
Wdym
like is there a method so that a user that runs a command that replies to a thread, can pass a message argument to a method to automatically do that ?
like if I were to use a method to make a command pass a message onto a user who started a thread
So you want the user that created the thread?
you mean in the def message chain
!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, I want another person, a moderator+, to be able to reply to the person who started the thread's thread. So if a user runs a command to start a thread in dms with the bot, that message will be passed onto the moderator/staff of that server, and the moderator can reply to that thread
that's my end goal, I could just copy some code from github, but I want to write this kind of stuff on my own, since I haven't work with d.py in ages lmao
is there a method for that?
Yeah, he goes to the thread and clicks join ๐
no, I want the mod to receive a dm with the message, and this way they can reply to the specific user through the bot, such as passing their message in dms with the bot, and the bot will then pass the message back to the user who sent the report.
that's the point of dms in moderation right? So you can report in private without others seeing your issue.
You can't create threads in dms
ah okay, so how can I achieve this end goal?
i might've seen wrong earlier on a os project on github, since I thought you had to create a thread in dms lmao
Simply make it so whatever the user sends a message in the bot's dm it takes the message and sends it somewhere else, either in a staff channel or in a moderator's dms
ok well ... nevermind
?
ah okay, how can I send something in dms lmao. I think there might be a built-in method for that, but I can't remember lol
As i already told the guy from earlier, .send on the member
I don't think I have to check whether it's in dms or a public channel, since the user can decide that, and with bots that run on d.py's built-in ability to run their commands with someone calling them in cdms.
!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**.
ah okay, thank you!
Yw
Check if the channel is a dm channel
and how can I do that?
!d discord.DMChannel
class discord.DMChannel```
Represents a Discord direct message channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channelโs hash.
str(x) Returns a string representation of the channel
ah okay, thank you!
Yw
Alr
so in the on_message event, I can simply check for whether or not the message sent is a dm message, or a channel message right?
and if it's a dm message, I can run the command?
yeah
Oh
the report feature
Then use ctx.channel
There is also a check im pretty sure for if a command is run in a dm
if isinstance(ctx.channel, discord.DMChannel):
...
ah okay
couldn't I just do that in a command itself
That's where you're doing it
okay, let me give it a shot. I will tell you how it goes.
!d discord.ext.commands.dm_only
@discord.ext.commands.dm_only()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.
This check raises a special exception, [`PrivateMessageOnly`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.PrivateMessageOnly "discord.ext.commands.PrivateMessageOnly") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
New in version 1.1.
ok now that might help me
ah okay, i think using a decarator would be more efficient
do I have to define this in the command that I want the decorator to accept, or?
@wicked atlas
Just import it, and then you can use checks on your command like this
@commands.command()
@dm_only()
async def my_command(ctx):
...```
Just make sure they go under the command() decorator
huh
its @commands.dm_only()
Well, unless you import the decorator
after you import from discord.ext import commands
But you could do that
ohk
never imported a decorator before, could you elaborate please?
Well, that was poorly worded, I just meant you could do either of the following
from discord.ext.commands import dm_only
from discord.ext import commands
commands.dm_only()
ah okay, that makes sense, thank you!
@bot.command()
async def avatar(ctx, member : discord.Member = None):
async with ctx.typing():
await asyncio.sleep(0.5)
if member == None:
member = ctx.author
memberavatar = member.avatar_url
emb = discord.Embed(color=0x2f3136)
emb.set_image(url = memberavatar)
emb.set_author(name = f"{member.name}", icon_url = memberavatar)
emb.timestamp = datetime.utcnow()
await ctx.send(embed = emb)
how do I create an animation of a bot so that it type after the command await await asyncio.sleep(0.5) and after that it has already written the code itself.


