#discord-bots
1 messages · Page 443 of 1
message.embeds returns list[discord.Embed]
🤨 then i gotta get it separately and get the description from that? rip
done hahaha i had imports i didnt use was on local downloaded but not on serve
im crying
hahaah
yes message.embeds returns a list of embeds the message has
hi..when ever i run my bot for testing it runs twice, even tho i run it once from cmd with python main.py , and i made sure that there is nothing running in the laptop's background.
anyone knows why?
i cant find the second instance.
also when i kill the cmd that i used to run the code, the bot goes offline..
wdym i didnt get it
so close the cmd then re-open it?
i use command promt
ok
i will try, thanks for the help
how to check guild premium tier in a tasks loop?
!d discord.Guild.premium_tier
The premium tier for this guild. Corresponds to “Nitro Server” in the official UI. The number goes from 0 to 3 inclusive.
U gotta get the guild with bot.get_guild and stuff
U gotta store the old value in a var and the new one in another one. Then compare them
something like before.guild.premium_tier in a tasks loop
Well there is no separate event for that tbh
on_guild_update 
It works for premium tiers also? Idk
!d discord.on_guild_update
discord.on_guild_update(before, after)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild") updates, for example:
• Changed name
• Changed AFK channel
• Changed AFK timeout
• etc...
Hmm, could be
maybe
Etc. Hmm, it isn't defined properly what all events are triggered. Idk, time to check the intents.guild
lol
yeah
my nitro will end soon :(
Mine in a week 
#bot-commands
don't blame me. Life is being weird
r-r-r really.... blushes
Did you just see a Beluga video...?
n-no
lol
Lmao
Hi
it updates the channels on a reboot
Hmm
but after that if i create a channel it wont update
ok so yall know that you can add join msg yeye
so i added a join msg but when i add this to it
@client.event
async def on_member_join(ctx):
role = discord.utils.get(ctx.guild.roles, name='chicoken')
await ctx.add_roles(role)``` Why i add this to the code, it doesnt show the join msg and doesnt show any error either
anyone can help?
on_member_join also takes a member as arg(member who joins), ur supposed to give it role
how do i
@client.event
async def on_member_join(ctx, member):
role = discord.utils.get(ctx.guild.roles, name='chicoken')
await ctx.add_roles(role)```
u mean like this mate?

Hi
hi
Kylee sad
what
Yep and member.add_roles
The emoji hehe
where?.. sorry for the noob questions im new to this xd
@maiden fable 
my mic died :(
Hm?
await member.add_roles(role)
u in a VC?
zoom class 
ah i c thanks
ah
@maiden fableanythingbro?
nope, sorry
Nothing 
@rare pewter should be able to help you (no sarcasm)
help include
Hunter bullying me 
If I knew about it I would helped
Fact is Hunter didn't taught me how to do that 
@client.event
async def on_member_join(ctx, member):
role = discord.utils.get(ctx.guild.roles, name='chicoken')
await member.add_roles(role)``` uh i tried this but it still didnt work
intents
Oh wait
and no need ctx
Remove ctx
so do i change ctx.guild.roles to?..
@spring flax
no you get member.guild.roles
can u?
i see thankoo
ok something is wierd
same problem again, no join msg- just the role is being given
?
members = guild.members, you sure you want this? or do you want the amount of members
members = len(guild.members)
Also, there is a membercount attr
@client.event
async def on_member_join(member):
role = discord.utils.get(member.guild.roles, name='chicoken')
await member.add_roles(role)```
intents
alr on
no error?
no join msg
cause you didn't send any?
i did
a join msg
you didn't tell it to send a message
@client.event
async def on_member_join(member):
channel = client.get_channel(883251215637561399)
await channel.send(member.mention + "has **__joined__** the server!")```
eh
normal user, my name is polite
will it count if the member is a bot or not while using len?
also you can use f strings
await channel.send(f"{member.mention} has **__joined__** the server!")
@lone aurora
bots will be counted
i did that so it can know if the member is a bot or user as u can see
yea i use them in some places but i like to keep it in + in some places ._.
note, it's member_count
but will it work same if i do len?
mb
and the issue at hadn is it is not updating the channel
ah finally it shows up, very pog very pog thanks a ton @spring flax
hand
and now it updated the channel after like 5 mins or more suddenly
when it should just update every 60seconds
is it because i am getting blocked somehow?
uhh
ok nvm its not working
its more or less same
what's wrong now?
line 26, in on_member_join
await member.get_roles(role)
AttributeError: 'Member' object has no attribute 'get_roles'``` prolly something simple but im dumb
hm
await member.get_roles(role)```
!d discord.Guild.get_roles
!d discord.Guild.get_role
get_role(role_id)```
Returns a role with the given ID.
iterate through member's roles to find any
@client.event
async def on_member_join(member):
channel = client.get_channel(883251215637561399)
role = discord.utils.get(member.guild.roles, name='chicoken')
await channel.send(member.mention + "has **__joined__** the server!")
await add_roles(role)``` this should do it right:?
Member don't have any get_roles
oh yea i forgot to change that
You probably mean add_roles
discord.Guild cannot be used, it don't know anything about outside and is just a raw class
!d.member.role
then what do i do
!member.role
use guild's instance
member.roles to get the members roles
member.guild
eh what now
feed me im dumb
put @
So my question 
Suppose I'm running a task with 10 minute repeat delay and the task itself takes 10 seconds to complete, something like ```py
@tasks.loop(minutes=10)
async def foo():
await asyncio.sleep(10)
> The next iteration starts after `10 min 10 secs` or just `10 mins`?
> The docs say that `.cancel()` stops the currently running iteration. So which iteration is that? The `10 min` waiting one of `10 sec` which is currently running one?
remove the default one
read the error
and it should work?
bot = commands.Bot(command_prefix="a prefix", help_command=None)```
readed nothing commed in sense
k thanks
^ or better if you subclass HelpCommand and make one, but yeah both works
member.guild.roles
and
member.add_roles
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
It is not give_roles
Instead of trying to guess the function name probably you should go to the docs and find it
so i wanna use client in a cog
what do i do
cuz i need it for {client.user.avatar_url}
Assign client to a class variable
For example, self.client = client
Then you can use client as self.client
use self.client after self.client = client
ohh
ohhhh ty ty
gotta remember that for cogs HAHA
oh
u can just use that
bot.user.avatar_url instead of client
u have defined self.bot = bot right?
then u can jsut do everything with bot and forget the client
then just replace bot with client
if u wanna just wanna use client
but when i do {default} it shows default is not defined
like this
The client is passed by dpy in your setup function like ```py
def setup(bot): # or client or whatever you'd like to name it
And while initializing your cog, you can pass this bot/client into your cog class like ```py
def setup(bot):
bot.add_cog(MyCog(bot))
and your Cog should look like ```py
class MyCog(commands.Cog):
def init(self, bot): # init is the function where you pass your bot or any parameters you need to pass inside class
self.bot = bot # self makes this instance variable to be able to access in every method in the class
self.bot... # This is wrong! Since you don't have self defiend at your class level but you pass it inside every method, so it's accessible there
@commands.command()
async def foo(self, ...): # you have to pass self in every method of the class
self.bot # it's accessible here
class information(commands.Cog):
def __init__(self, bot):
self.client = bot
self.default = "."
@commmands.command()
async def botinfo(self, ctx):
embed = bla bla bla
embed.add_field(name="server prefix", value=self.default)
await ctx.send(embed=embed)
try that
oh
to access the default variable, you use self.default
https://realpython.com/python3-object-oriented-programming/ Have a look at this
self basically tells Python where to search the variable
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
bot.user.mentioned_in in on_message
x means the variable x, outside the class. self.x means the variable x, but the one that belongs to the class
wdym
someone
help
belongs as in the one initialized in init
i'll read
define guild
to what
thats wht i dont know
send an example structure of the json file
👀 ..
just this []
bro stop
tell me to wht should i define guild to
what if my prefix is prefix = ['.', '!']? do i do commands.when_mentioned_or(prefix)
nono, what I mean is the example of a filled json
like [1232...]
guild = ???
example like {"ID": "prefix"}
or is there nested dicts
send full code
add an asterick before the prefix like (*prefix), it's used to unwrap an iterable
okay
@waxen granite
guild = ctx.guild
thnx
thnx
wait, I actually don't really understand what your code is doing tho
well i am counting a role mentioned in msgs in a channel
and dumping them in a json to keep the count
if i want to change this to client.command cause i use it wil this work
my whole code is in client.command
uhh now i did the same for another cog but idk why the editor showed an error
will it break my code

What error?
anyone
wdym?
@quaint axle.event to client.command?
bro will it work cause i use client.command and this is on_message
no
then wht should i do
make a seperate command
event and command are different
that’s basic OOP
class help(commands.Cog):
def __init__(self, bot):
self.client = bot
i did this
Have a look at that link, it has all the basics related to oop and classes
okay
That's fine, it's just the bad naming
@waxen granite will this work
self.xyz = bot will also work, but it's not good to name like that
bro can anyone tell him to unblock mee
hmm
will it work
stop spamming
sorry
sis
and idk
ohk i will try it out
thnx btw
hello everyone
Hii 👋
hey
is SB | HIMUNOID the one you don't like?
I understand where you're coming from, though avoid language like "tard" as this is demeaning for people with disabilities.
some of whom might be members of our server.
It's fine just don't bother much if someone is annoying you. They used to mass ping me with emojis so I just blocked them
well, now you know for next time
So anyone?

why not use an event?
Uh you can't create tasks with an event. Also I don't make bots, it's just like, want to know
10 min 10 seconds should be it
anyone?
i am counting a role mentioned in msgs in a channel
and dumping them in a json to keep the count
Yo @slate swan do u use VSCode with GitHub?
Ah I see, Thanks.. You know about the second question too?
if u are making it sleep then just make it sleep for 10 mins and repeat.
VSC with Github?
you mean the extension
should be currently running one, but I don't know properly, sorry
mhm
events don't work that way.. those are received via gateway, and how am I supposed to create a timed task with an event
lmao
well you can use bot.dispatch() but I don't see any use tbh
Bro "timed task" (which repeats after every 10 mins)

Anyways
i wonder why dont i see yellow colours in chat now a days
I mostly use Github Desktop instead of extension
oh. cz I am getting this weird thing in the Pull Request extension
yellow colours in chat? You mean helpers?
yeah
Haha
Mhm
I don't even know properly about github
I once deleted the whole fork and reforked coz I can't understand some particular thing lol
Lmao
ping again. HAllp!
nvm it is fixed
Why did you reset rolecount to 0 tho
You shouldn't open the file on every message anyways
where 😮
i did not, its only there in the whole code
Does anyone know why ctx.guild.owner returns none?
Well you do open the file on every message
prev count as 0 ?
?
start as 0
So after you save it it becomes 0
ah u mean like that, i am dumb :3
import discord
from discord.ext import commands
from datetime import datetime
from discord import Embed, Member
from discord.ext.commands import command
client = commands.Bot(command_prefix = '-')
intents = discord.Intents.default()
intents.members = True
intents.guilds = True
class FunctionUserInfo(commands.Cog):
def _init_(self, client):
self.client = client
@commands.command(pass_context = True)
async def serverinfo(self, ctx):
embed = Embed(title = "Server information",
colour = 0xFF5733,
timestamp = datetime.utcnow())
embed.set_thumbnail(url=ctx.guild.icon_url)
fields = [("Owner", ctx.guild.owner, True)]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
await ctx.send(embed = embed)
def setup(client):
client.add_cog(FunctionUserInfo(client))```
Anyone know why owner prints None?
hm
You never gave the intents in the bot constructor
Add intents=intents in the bot constructor
:oooo
Guild.owner returns None when the owner's member object isn't found in the cache (due to missing intents) or sometimes it can be possible when discord itself removes/forbids the owner from the guild
I still don't understand why people name their Bot object variable client 
YouTube Tutorials

Yep YouTube tutorials
So like this?
intents = discord.Intents.default(intents = intents)
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
I see thanks!
No problem.
Where are you using these imports?
from sys import float_repr_style,import discord,from discord.ext.commands import command,from discord import Member...
You're naming your Bot as client
You defined intents later and not passed them inside the constructor
Your method__init__is written as_init_
pass_context=Trueis decrapted..
This is probably some copied old code.
He created his own language, it's okay.
👀
Wait yes, your cog is in the same file and you're still using setup? And passing client in class? Dude 
And how it even prints something?
Nvm have a look at https://vcokltfre.dev/ for dpy guide, and if you don't know about python or oop, don't try dpy before learning that
That's an astronomical way of making Discord bots. It's too advanced for us.
hey, i was to covert text to emojis like this a = 🇦 so the command would be something like !texttoemoji abc and the output would be 🇦 🇧 🇨
!charinfo #bot-commands
quick question
You'll have to make a dictionary of all the emojis and their character information displayed there
how do i reply to a message? with the message object or ?
!d discord.ext.commands.Context.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/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Message "discord.Message").
New in version 1.6.
Example, await ctx.reply("Hello!")
i do not have ctx
How to check if a bot is verified?
can i do it with a Message
message.reply? yes
like an await message.reply()
of course
sweet thanks
what other stuff can be logged? I am tryna use on_member_update and user update but rn only have it so if they change their nickname it shows the before and after
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change...
@cog_ext.cog_slash(
name="extens",
description="Load, unload or reload an extenion.",
guild_ids=[832595290174914571],
options=[
create_option(
name="load",
description="Load an extenion from the bot.",
option_type=3,
required=False,
choices=[create_choice(name=cog.split(".")[-1].capitalize(), value=cog) for cog in (c.BOT_EXTENSIONS + ['all'])]
),
create_option(
name="unload",
description="Unload an extenion from the bot.",
option_type=3,
required=False,
choices=[create_choice(name=cog.split(".")[-1].capitalize(), value=cog) for cog in (list(filter(lambda x: x not in c.BOT_EXTENSIONS_UNLOAD_BLACKLIST, c.BOT_EXTENSIONS)) + ['all'])]
),
create_option(
name="reload",
description="Reload an extenion from the bot.",
option_type=3,
required=False,
choices=[create_choice(name=cog.split(".")[-1].capitalize(), value=cog) for cog in (c.BOT_EXTENSIONS + ['all'])]
)
]
)
``` i got this now but the user can now pass this if no option is selected and the user can select multiple options, anyone a solution?
@commands.command(description="Remove a word from the blacklist", aliases=['removeword'],usage="<word>")
@commands.has_guild_permissions(administrator=True)
async def unblacklistword(self, ctx, word:str = None):
if word is None:
return await ctx.send("Give me a word to unblacklsit")
if word not in self.client.blacklistdata["blacklistedWords"]:
return await ctx.send("Word is not blacklisted")
self.client.blacklistdata["blacklistedWords"].remove(word)
await ctx.send(f"Removed `{word}` from blacklist")
self.client.blacklistdata = utils.jjson.read_json("blacklistedWords")
why does this not remove the word from the json file?
have you considered using a database instead?
is aws somewhat decent for hosting a bot?
it's good
Have you tried it?
If you mean that they are able to use the command without filling any of the options, then it's because you have required=False on all of them. Change it to required=True.
Never heard of it but I know this great free and paid hosting. https://somehost.xyz
Free and paid hosting
status = member.status
if status == "online":
new_embed.add_field(name="Current Status:", value=" online")
elif status == "idle":
new_embed.add_field(name="Current Status:", value=" idle")
elif status == "dnd":
new_embed.add_field(name="Current Status:", value=" dnd")
elif status == "invisible" or status == "offline":
new_embed.add_field(name="Current Status:", value=" offline")
else:
pass
i did this but it does not seem to work
it doesnt show in the embed
didn't send it
if i do that i'd need to fill them all in resulting in the mutliple options error
if status == discord.Status.online
if status == discord.Status.idle
if status == discord.Status.dnd
if status == discord.Status.offline
This would be better.
I'm not sure what you exactly need. I assumed that you want them to have to fill all of them.
the bot is for a single server so i think i json file will be fine
I only need one filled out.
Use choices.
A server ban log doesn't log who actioned a ban does it? Would the audit log do that?
One option with multiple choices. In choices, only one can be chosen.
trying to do a .addrole command but it is saying it cant convert user into Member or User
!d discord.AuditLogAction.ban
how did you invoke the command?
A discord.User object does not have an add_roles attribute, does it?
anyone?
that would be member
No
!d discord.User
class discord.User```
Represents a Discord user.
`x == y` Checks if two users are equal.
`x != y` Checks if two users are not equal.
`hash(x)` Return the user’s hash.
`str(x)` Returns the user’s name with discriminator.
and member wouldn't be an argument of the function, but the function would be the attribute of member
I meant via the await fetch ban(s) not the actual ban event. I have a load of bans that aren't logged by the bot so I want to go through and log them
oh okay ty
Reason- A User can be in more than one guilds and the Bot doesn't know in which guild to add the roles?
but I don't see the reason of using user in a command
so how can I fix my error?
you can get member which knows even more things
Looks really shady
Why?
I've been using it for a while now and it's pretty great. 
@dapper cobalt how can I fix the Could not convert "user" into Member or User.
You don't need discord.User, only discord.Member.
oh ok
@dapper cobalt when I do .addrole @proven elm test
it says there is no member "test"
so I then tried doing .addrole test @proven elm
but it gave me an error related to strings
Show me your code again please.
async def addrole(ctx, member:discord.Member, role:discord.Role)
ty
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
It's member.add_roles(role).
is there a way to manually raise the on_command_errorcommands.MissingPermissions
What do you think is the problem?
raise commands.ErrorName.
ctx.member.add_roles?
that isnt triggerieng the MissingPermissions error handler i have :/ does it raise a different one?
positional arguments
you gotta sort them correctly 
I mean in the command's arguments
!source eval
Run Python code and get the results.
@client.event
async def on_guild_channel_create(channel):
while True:
await channel.send(random.choice(message_spam))
@client.event
async def on_guild_channel_create(channel):
webhook =await channel.create_webhook(name = random.choice(webhook_names))
while True:
await channel.send(random.choice(message_spam))
await webhook.send(random.choice(message_spam), username=random.choice(webhook_names))```
is there anything wrong with that?
the webhooks wont create
any error?
yeah
ik
its supposed to be a message spammer
its not for malicious use tho
sus
dont worry
its to troll a friend
and im using a public spammer
im pretty sure its still against tos lmao
aw
:(
k
ty
also, can you even have multiple events of the same thing?
idk...
im new to python
okay, let's not help with this tho
@client.event
async def on_guild_channel_create(channel):
while True:
await channel.send(random.choice(message_spam))
webhook =await channel.create_webhook(name = random.choice(webhook_names))
while True:
await channel.send(random.choice(message_spam))
await webhook.send(random.choice(message_spam), username=random.choice(webhook_names))
by the fact you use client, i could guess lmao
trying to do .addroles @proven elm ROLEGOESHERE but getting an error
bro switch the arguments
the first parameter is Context
im back
Dude what are you even trying to do 
its a message spammer to spam my friend
bc he did it to me
@proven elm ctx, member: discord.Member, role: discord.Role, reason=None, atomic=True
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
I don't think we can help you with this
Sweet revenge.
encountering this now
lol ctx.member
oh my bad that was an accident lol but ye it works now thank you
Is there any way to prevent duplicated messages in a message?
is there a way to prevent multiple words inside the same message*
Read the message content and check for similar words
Ok
I don't think there's a built-in non-algorithmical way for that
Alright
like how would you prevent
hellohello
unless its seperate words im pretty sure its impossible lmao
Nah it's still possible
hello hello
you would just save the string in a list and check for something that's there multiple times
mhm
yes but creating a function based to purely see a pattern in words would be faulty cuz what about stuff like
whawhy
as an example the first 2 letters would be seen as a "dupe"
https://github.com/Skelmis/DPY-Anti-Spam If you're lazy to make one like me, use this
Yeah it can not be 100% accurate but you can do that for longer matching patterns like 10 same letters in a word
still wouldnt be precisely what he wants making it impossible to create the exact function lmao
as per self developing api lmao
Megszentségteleníthetetlenségeskedéseitekért
delete this nice word for no reason
man
Make a neural network and train it by self spamming 
so self developing api lmao
just delete every message
ok.
lol
smart
Or ```py
@bot.event
async def on_member_join(member):
await member.ban(reason='Potential Spammer')

lmao
and check if they are a spammer
Just don't let anyone join the guild, spam free server

imagine getting verified with a server like this
How would I go about not letting myself use .ban user more then once cause if I do .ban @proven elm twice or an infinite amount of times it does ctx.send("Banned user") repeatedly rather then saying "USER IS ALREADY BANNED"
I'm pretty sure it would throw an error
and you can't mention somebody that's not in the guild
you can
nah I mean if I do .ban 89059375935703
like an ID
it will keep giving the "Banned user" even if I banned them already
you wouldn't be able to get the member
yes but it gets the user
but why would you ban somebody with user
what do i need to fix in this?
var1 = get(client.guild.roles, name = "Introvert")
var2 = get(client.guild.roles, name = "Ambivert")
var3 = get(client.guild.roles, name = "Extrovert")
var4 = get(client.guild.roles, name = "Omnivert")
if they leave the discord before youre able to ban them?
then they try rejoin later they wont be able to?
Yes
member = guild.get_member(id)
if member is None:
#he not in the guild
else:
#ban him
You can ban users not in guilds too
This can return None in more cases like missing intents or cache thingy
I don't think the cache affects this
what does None mean? not in guild
Anybody bothering to help.....
you can ban people outside a guild
Imagine getting privileged intent to check if member exists 
if member is none means if theyre not in the guild?
Maybe... try to fetch the bans and check in that..?
!d discord.Guild.fetch_ban
await fetch_ban(user)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the [`BanEntry`](https://discordpy.readthedocs.io/en/stable/api.html#discord.BanEntry "discord.BanEntry") for a user.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
ahh
I mean-
you would have to anyways
Anyone....
when banning you can try except for HTTPException
client.guild is nothing, it's client.guilds which returns a list of guilds
ummm? am confused.... i just want to fetch the roles from the guild
and mention them
@client.command()
@commands.has_any_role("staff", "Administrators")
async def poll(ctx,*, opt):
var1 = get(client.guild.roles, name = "Introvert")
var2 = get(client.guild.roles, name = "Ambivert")
var3 = get(client.guild.roles, name = "Extrovert")
var4 = get(client.guild.roles, name = "Omnivert")
emb = discord.Embed(title="Poll", description=f"{opt}", color=discord.Color.from_rgb(255, 255, 0))
mes_channel = client.get_channel(882579676206358558)
embedmsg = await mes_channel.send(content=f"{var1.mention}, {var2.mention}, {var3.mention}, {var4.mention}", embed=emb)
await embedmsg.add_reaction("👍")
await embedmsg.add_reaction("👎")
yes
use ctx.guild
thenku

Is this a glitch or something? 
Why am I SERVER in message reference?
ya known bug since the first time reply started rolling out
never fixed
Oh lol, experienced this first time
!d type
why am I getting this?
tryna fetchbans so I can make it a boolean to see if people are banned
full traceback?
How to black list a role
@agile goblet
Does anyone are looking a parther to create a bot?
Yes dms
hey, so i have an embed with fields in it, i wanna set the title of the fields to links. ive been using the markdown syntax display but i keep getting the actual syntax in the msg, is there anyway to fix this?
how do i make the bot's status say watching
!d discord.ActivityType.watching
A “Watching” activity type.
whyd u name ur context argument guild
await client.change_presence(
activity=discord.Activity(type=discord.ActivityType.watching),
name=what they are watching
)
How to black list a role
thanks 
hm?
Could you elaborate more on this?
Sure
Ignore de code if user has a specified role
the first argument passed in a command is always a discord.Context instance
For example antiinvites only for members but not for owners
youre using it as if its a discord.Guild instance
Either add a check decorator to the commands you want this to have or use on_message to check the author roles
to get that from a Context instance you'd have to do guild.guild or normally ctx.guild
Tried much things but couldnt make it work
Thats why im asking here.
Show me
ok in dms? you can answer me here
Are there any good alternatives to asyncpraw because I'm having.some issues with it
What issues?
for role in member.roles:
if role.id == 880776769546883123:
return False
return
else:
pass```
```await blacklist(message.author)```
Asyncpraw is like the go to
Thats what i used and didnt work
Very little documentation, extremely slow, no way to filter out gifs, images and videos, can't filter nsfw, images sometimes just straight up break
Redundant return, for loop when in could be used, the else is just pass, so it could be left out
I have a feeling you don’t have a lot of python experience
i dont..
would anyone be able to help?
Can you send an image of it?
You are aware dpy is extremely complex and pretty much requires you to already have quite a bit of python experience to really work with it?
A discord bot is a very bad first or early project due to how complex they are
Nah
Ikr just want someone to help me build a simple black list role code...
Explain what you want it to do
Ignore code when user has a given role
for example:
anti invites only for members and not for owners
wich means if you have owner role code will stop working in that code
Can you send the code?
.
So what's showing up that you don't want it to
yeah
i just want Google but have it as a link
not sure why this isnt working cause i thought discord supported markdown
Water_Gazes can you at least say if youll help me or not cause i feel like beeing heella ignored right now..
If you just wanted a link them remove everything except google.com
ill try that
whaii is it not working
help me :/
Read.
Last line of your error says what's the issue.
i have a command >react [msg id] [emoji which react to the msg but i want if specify the msg id so bot will react to the last msg :/
bro i dont understand
Read the last line of your error.
r u new to python?
yes
but did u see the file in left side of image
Can someone help me build simple blacklist role code please
sometimes this happens also after giving the right path idk why :/
Is it in the same directory as your python file?
u use vscode?
yes
What's the directory's name?
which theme r u using :/
whai u asking that thing
Try cogs/prefixes.json.
its not cog
i want a good theme for me 😓
@dapper cobalt Could you help me.
Isn't the directory's name "cogs"?
try HIMUNOID/prefixes.json
Ah. I'm not very sure then.
i have a command >react [msg id] [emoji] which react to the msg but i want if specify the msg id so bot will react to the last msg :/
Im getting ignored hard 🙂
:/
Can Someone Help Me.
Don't ask to ask just ask.
Build a simple blacklist role code.
@dapper cobalt :/
We don't spoonfeed. Try to make it yourself and if you face issues you can ask.
I don't understand what you mean.
Errors?
for role in member.roles:
if role.id == 880776769546883123:
return False
return
else:
pass```
```await blacklist(message.author)```
no errors are given
Where is your decorator?
idk what you mean
And why are you returning twice?
@client.command() or @bot.command().
i have a command >React [message id] [emoji] by that the message get reaction by bot but i want the bot should react to the latest msg if member will not provide the msg id
in another code
do i send it too
@bot.listen("on_message")
async def on_message(message):
if "NoLI" not in message.channel.topic:
return
if message.author.bot:
return
else:
if "discord.gg" in message.content.lower(
) or "https://discord.gg/" in message.content.lower(
) or "https://discord.gg" in message.content.lower():
await blacklist(message.author)
await message.channel.purge(limit=1)
await message.channel.send(
f" {message.author.mention} Discord links are not allowed here!",
delete_after=10)```
how do i make one of these interactive times
@dapper cobalt theres the other code
<t:timestamp>
is there a list of all of those somewhere?
yeah there are a few
!e
from datetime import datetime
print(round(datetime.now().timestamp()))
@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.
1630679842
anyone know why i get this error with pyinstaller?
https://cdn.discordapp.com/attachments/828686085395316746/883358730966687794/unknown.png
KeyError are you able to help or Not
i am so shit at drawing arrows
Doesn't look like a discord bots related question.
bruh
idk where to post tbh
kk
You are returning which breaks the entire for loop.
Use continue instead.
i replace return with continue
for x in x2:
if x == y:
# do something
else:
continue
right?
i meant pass with continue sorry
for role in member.roles:
if role.id == 880776769546883123:
return
else:
continue```
code looks like this now it doesnt work yet
Anything that comes after return will not function since return breaks it.
Is it supposed to stop the for loop if the role id is equal to that id?
to ignore it
Again, return will completely stop the loop.
ok so i replace return with continue
Yes.
theres a continue at the and what i do with it
What is it supposed to do if the role id is not equal to that id?
I don't suggest making it do checks inside a function. Move that code into the event and it will be easier.
@bot.listen("on_message")
async def on_message(message):
if "NoLI" not in message.channel.topic:
return
if message.author.bot:
return
else:
role = message.guild.get_role(880776769546883123)
if role in message.author.roles:
return
if "discord.gg" in message.content.lower():
await message.delete()
await message.channel.send(
f":warningg: {message.author.mention} Discord links are not allowed here!",
delete_after=10)
There.
Thank you so much.

worked!
Great.
now = datetime.now(timezone.utc)
created_delta = now - target.created_at
i got this error, target is ctx.author
Try to print target.created_at and now.
ok
Convert them into timestamps.
both?
Yes.
I’m trying to make a meme command with the Reddit api but whenever I try the command, it only returns “loading meme…” and not the actual meme. Can someone help?
@commands.command()
async def meme(self, ctx, subred = 'meme'):
message = await ctx.send("Loading meme...")
reddit = asyncpraw.Reddit(client_id='PISz3Th_jhJ3702YybyQgA',
client_secret='o8Joul44CngHjOwfKjqz3H_a0QRdYA',
username='python_praw123',
password='python123',
user_agent='pythonpraw')
subreddit = await reddit.subreddit(subred)
all_subs = []
top = subreddit.top(limit=100)
async for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
embed = discord.Embed(
title=f'{name}',
color=ctx.author.color,
timestamp=datetime.utcnow(),
url=url
)
embed.set_image(url=url)
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
embed.set_footer(text=f'r/{subreddit}')
await ctx.send(embed=embed)
Just use simple JSON API
Huh?
Try to print random_sub.
And btw, datetime.utcnow() doesn't return a timestamp. Make it round(datetime.utcnow().timestamp()).
client_secret exposed.
Regenerate it
Is it that dangerous?
Is that the reddit client's secret or the bot?
Ah okay.
That's Reddit not the bot token. Bot tokens don't look like that.
can i get the banned users avatar from await guild.bans() ????
It returns BanEntry object which does include a discord.User object, so yes.
!d discord.Guild.bans
await bans()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves all the users that are banned from the guild as a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`BanEntry`](https://discordpy.readthedocs.io/en/stable/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
!d discord.BanEntry
class discord.BanEntry```
A namedtuple which represents a ban returned from [`bans()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.bans "discord.Guild.bans").
i use this
How do I modify the property of a subclassed list? Like I need it to return the main list with an added item everytime I print it. 
👀 Wait it's discord help, nvm
self.append(item) and return self
where?
Like which method?
class X(list):
def __init__(self):
super().__init__()
x = X()
print(x)
I need to change it's behaviour to return the main list
open a help channel
Sure, Thanks
right click prefixes.json and click "Copy relative path"
Enter that path to the open function
same error
Anyone know what's the issue?
DEFAULT_BADWORD = 'fuck'
async def on_ready(bot, message):
if not message.guild:
return DEFAULT_BADWORD(bot,message)
badword = await bot.db.fetch('SELECT badword FROM guilds WHERE guild_id = $1', message.guild.id)
if len(badword.id) == 0:
await bot.db.execute('INSERT INTO guilds(guild_id, badword) VALUES ($1, $2)', message.guild.id, DEFAULT_BADWORD)
badword = DEFAULT_BADWORD
else:
badword = badword[0].get("badword")
return badword(bot,message)
async def create_db_pool():
bot.db = await asyncpg.create_pool(database = "tutorial", user = "postgres", password= "20266137")
print("Connected to the DataBase.")
@bot.command()
@commands.has_permissions(administrator=True)
async def add(ctx, *, badword):
await bot.db.execute('UPDATE guilds SET badword = $1 WHERE guild_id = $2', badword, ctx.guild.id)
await ctx.send(f"The badword has been updated! New badword: `{badword}`")
@bot.event
async def on_message(message):
badword = DEFAULT_BADWORD
for word in badword:
if message.content.count(word) > 0:
await message.delete()
embed = discord.Embed(title="Message Deleted", color=0xD708CC, description= f"{message.author.mention}, You're not allowed to say that.")
embed.timestamp = datetime.utcnow()
await message.channel.send(embed=embed)
await bot.process_commands(message)
bot.loop.run_until_complete(create_db_pool())```
That key doesnt exist
It's deleting random stuff. I have no errors
I want to make it so if any word is in the badword aka DEFAULT_BADWORD the bot will delete the message.
How can I fix this?
The second one doesn’t work for me for some reason but the datetime.utcnow() works
Ah okay then.
Guys I currently have a code that lists all roles:
", ".join([str(r.mention) for r in ctx.guild.roles])
Does anyone know how to remove @@everyone
It lists all but it also prints out@@everyone
Where do I put that
You have to put await
you could put if r.name != "everyone"
The name of the role.
help :/
ask
Trying to check a specific message for a user to react to it.
def check(reaction, user):
if not user.bot:
if confirmation_message and reaction.emoji == "✅":
return True
elif confirmation_message and reaction.emoji == "❌":
return False
await bot.wait_for("reaction_add", check=check)
print("Check complete")```
The check never passes if someone reacts with ❌ . I'd like to return somehow that the user cancelled the action but haven't figure it out yet.
@bot.command()
async def react(ctx, chat:discord.Message, emoji):
if chat is None:
await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Message on which you Want to React")
else:
if emoji is None:
await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Emoji which you want to React")
else:
message = chat
await message.add_reaction(emoji)
i want that is chat will be None so bot should react to the last msg of the channel :/
Yea but can u even delete messages from the bot?
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
@bot.command()
async def react(ctx, chat:discord.Message, emoji):
if chat is None:
await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Message on which you Want to React")
else:
if emoji is None:
await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Emoji which you want to React")
else:
message = chat
await message.add_reaction(emoji)
i want that is chat will be None so bot should react to the last msg of the channel :/
how do you pass in a message object in a command
how can i know when a member joined on server? and is possible to set it as UTC+2
Lemme rephrase, I can't add an if statement in a parameter
!d discord.TextChannel.history with this you can specify the last message tho
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/stable/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
msg id :/
", ".join([str(r.mention) for r in ctx.guild.roles if r.name != "everyone"])
@stiff knot
if that works then nice, just use the tag to get the last message of a textchannel
.
k
what is history?
the last messages of a text channel
that wht are - limit,after and others?
there's probably a better way to do it
print("tax")
limit is like limit in discord.TextChannel.purge()
works the same way
It’s not working .—.
It still display @@everyone :/
@steep estuary I'm dumb, just use the last_message attribute
can i use async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None): inside
@bot.command() async def react(ctx, chat:discord.Message, emoji): ??
!d discord.TextChannel.last_message
last_message```
Fetches the last message from this channel in cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either [`history()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel.history "discord.TextChannel.history") or [`fetch_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel.fetch_message "discord.TextChannel.fetch_message") with the [`last_message_id`](https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel.last_message_id "discord.TextChannel.last_message_id") attribute.
:/
does it have two @'s?
last_msg = discord.TextChannel.last_message() ??
use ctx.channel
yeah
or how you have your channel defined
where?
U want to see my code?
oo
from discord import client
from discord.ext import commands
from datetime import datetime
from discord import Embed, Member
class FunctionUserInfo(commands.Cog):
def _init_(self, client):
self.client = client
@commands.command(pass_context = True)
async def serverinfo(self, ctx):
embed = Embed(title = "Server information",
colour = 0xFF5733,
timestamp = datetime.utcnow())
embed.set_thumbnail(url=ctx.guild.icon_url)
fields = [("Owner", ctx.guild.owner, False),
("Created At", ctx.guild.created_at.strftime("%d/%m/%Y %H:%M:%S"), False),
("Member Count", str(len([m for m in ctx.guild.members if not m.bot])) + " Humans | " + str(len([m for m in ctx.guild.members if m.bot])) + " Bots | " + str(len(ctx.guild.members)) + " Total", False),
("Region", ctx.guild.region, True),
("Text Channels" + "[" + str(len(ctx.guild.text_channels)) + "]", ", ".join([str(r.mention) for r in ctx.guild.roles if r.name != "everyone"]), False)
]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
await ctx.send(embed = embed)
def setup(client):
client.add_cog(FunctionUserInfo(client))```
U see the text channels?
Thats supposed to be roles but ye u get the point
There's 2@s
just put the exact name of the role instead of that string
if r.name != "name of the role"
It's because the everyone role's name is @everyone and mentioning it will be @@everyone.
I won't be able to put in different servers though
Yeah I realised when I checked the roles on my server XD
how did you send that
``
Python bot got angry at me for putting everyone ping in the codeblock
@slate swan != @DiaPikachu#1000
@everyone
lmao
dunno what I did then

you don't even have permission to ping everyone
it's like having 2FA verification on localhost
u want @ only
what did you do
why is it not banning user via their ID?
do you have MessageNotFound defined?
annyone down to help in #help-corn
damn it
the command is >react [message id] [emoji] which react to the message but i want if member will not specify the msg it should react to last msg :/
when i am not specifing message id it is showing error :/
I think you meant
except commands.errors.MessageNotFound
k :/
not ctx.discord.TextChannel
and last_message isn't a function
@client.command()
async def winners(ctx, **kwargs):
role = discord.utils.get(ctx.guild.roles, name="$u-h4ck3r")
if role is None:
await ctx.send('This server is not running `super-user` ctf challenge.\n'
'Type: `sudo su`')
return
empty = True
#for member in ctx.message.guild.members:
for guild in client.guilds:
for member in guild.members:
if role in member.roles:
await ctx.send("{0.name}: {0.id}".format(member))
empty = False
if empty:
await ctx.send("Oops this server has No winners :(\n"
"Type: `sudo su`".format(role.mention))
``` right now this code is sending (member_name and id one by one) ..takes too much time and also this is being abused...i want send the output in text file. i want to fetch all the member name and id who as specific role in guild ...and then send it in a text file.
you don't call it

I misread 









