#discord-bots
1 messages Β· Page 442 of 1
am i in a cog?
then you gotta import it
cuz im not?
No need
If you do that you must define it
i'm really confused due to his code. he said hes not in a cog file but then he proceeds to send a pic that has a cog file
from discord.ext import has_permissions
If you're not in a cog file, why did you put self?
let's just fix the problem that we have now and then move on
remove the self argument
and it should work
press on the cog file what does it contain ?
oh alright
lemme fix ur code 
thanks
I need some help on my mute command. Im getting an unknown role error when I have the role only guess to why its happening is im not searching for the roles correctly. Here is my code
@commands.command()
@commands.has_permissions(manage_roles=True)
async def mute(self, ctx, member: discord.Member=None, *, reason=None):
member = member or ctx.message.author
muted_role = discord.utils.get(ctx.guild.roles, name="muted")
await member.add_roles(member, muted_role)
if reason == True:
embed=discord.Embed(description=f"{member} was muted for {reason}.",
color=0xff0000,
timestamp=ctx.message.created_at)
embed.set_author(name=f'{member}', icon_url=f'{member.avatar_url}')
embed.set_footer(text=f"Epic Bot | Discord bot", icon_url='https://cdn.discordapp.com/embed/avatars/1.png')
await ctx.send(embed=embed)
if reason != True:
embed=discord.Embed(description=f"{member} was muted.",
color=0xff0000,
timestamp=ctx.message.created_at)
embed.set_author(name=f'{member}', icon_url=f'{member.avatar_url}')
embed.set_footer(text=f"Epic Bot | Discord bot", icon_url='https://cdn.discordapp.com/embed/avatars/1.png')
await ctx.send(embed=embed)
did you type the role name correctly?
it's case sensitive
ik
okay
@bot.command()
@commands.has_permissions(administrator=True)
async def ban(ctx, member:discord.Member, *, reason=None):
guild = ctx.guild
author = ctx.message.author
if reason == None:
embed1=discord.Embed(color=discord.Colour.red(), title="Reason Required!", description="You must enter a reason to ban this member.")
message3 = ctx.send(embed=embed1)
sleeper=5
await asyncio.sleep(sleeper)
await message3.delete()
return
else:
guild = ctx.guild
await member.ban()
embed2=discord.Embed(color=discord.Colour.green(), timestamp=datetime.datetime.utcnow(), title="Member Banned", description=f"Banned: {member.mention}\n Moderator: **{author}** \n Reason: **{reason}**")
embed3=discord.Embed(color=discord.Colour.green(), timestamp=datetime.datetime.utcnow(), title=f"You've been banned from **{guild}**!", description=f"Target: {member.mention}\nModerator: **{author.mention}** \n Reason: **{reason}**")
message4 = await ctx.send(embed=embed2)
message5 = await ctx.send("β User has been notified.")
sleeper=5
@ban.error()
async def ban_error(ctx,error):
if isinstance(error, MissingPermissions):
await ctx.send('you dont have perms to use this command')
else:
ctx.send('there was a error')``` @slate swan
oh
you put member in the args
remove that
didn't work
you called the member's method, so there's no need to define him inside the function
Theres an issue with that
its cuz of ur logic that you used there.
Traceback (most recent call last):
File "C:\Users\\Desktop\TMG Bot\TMG_Bot.py", line 487, in <module>
@ban.error()
TypeError: error() missing 1 required positional argument: 'coro'
PS C:\Users\\Desktop\TMG Bot>```
!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.
I use member: discord.Member to make the embed look nice

oh
Oh remove the parameters i'm sorry after the @ban.error() remove the () should look like this @ban.error
I was kinda inunderstandable again....
Alr and do you happen to know the function to dm a user?
i think to dm someone
yeah, that's what it does...
Hi
hello
So basically I have a tempban command. It works perfectly fine but I would just like to make the default time permanent. So lets say somebody bans someone without a time it would just default to permanent.
Could I get some help starting out on that
this is prolly stupid question how do i make it where the bot can only message in 1 channel?
@bot.command()
async def temp_ban(ctx, user:discord.User, time:int=100000000000000):
I don't think that would work
um. what?python @bot.event asyc def on_ready(): print('Signed in as', bot.user.name)
main.py", line 35
asyc def on_ready():
^
SyntaxError: invalid syntax```
async def on_ready():
You missed an n
@bot.check
async def bot_check(ctx):
commands = ['specific']
if ctx.command.name in commands:
if ctx.channel.id == <your_channel_id>:
return True
return False
return True
@bot.command()
async def specific(ctx):
print('worked')```
thank you sir
oh
why
i dont know how you did your tempban so it really depends
I can send the code
Idk how to explain it
to be honest im too tired and i've been helping people all day, so you can send it but i wont help with a long thing
Its not long
send it then
@commands.command()
@commands.has_permissions(ban_members=True)
async def ban(self, ctx, member : commands.MemberConverter, duration: DurationConverter, *, reason=None):
multiplier = {'h': 60**2, 'hour': 60**2, 'hours': 60**2, 'd': 60*1*60*1*24, 'day': 60*1*60*1*24, 'days': 60*1*60*1*24, 'w': 60*1*60*1*24*1*7, 'week': 60*1*60*1*24*1*7, 'weeks': 60*1*60*1*24*1*7}
amount, unit = duration
await ctx.guild.ban(member, reason=reason)
if reason == None:
await ctx.send(f"Banned {member.mention} for {amount}{unit}")
await asyncio.sleep(amount * multiplier[unit])
await ctx.guild.unban(member)
if reason != None:
await ctx.send(f"Banned {member.mention} {amount}{unit}. Reason: {reason}")
await asyncio.sleep(amount * multiplier[unit])
await ctx.guild.unban(member)
ok, then why doesn't this work:python @bot.event async def on_ready(): print('Bot is ready as: {}'.format(bot.user.name)) await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="your stupid requests"))
?
same error btw
I also have this
class DurationConverter(commands.Converter):
async def convert(self, ctx, argument):
amount = argument[:-1]
unit = argument[-1]
if amount.isdigit() and unit in ['h', 'hour', 'hours' 'd', 'day', 'days', 'w', 'week', 'weeks', 'm', 'month', 'months', 'y', 'year', 'years']:
return amount, unit
any errors?
I've been meaning to ask whats the point of using .format instead of just using an f string?
yes, :python File "main.py", line 64 async def on_ready(): ^ SyntaxError: invalid syntax
just do duration: DurationConverter == None
and then in the code
if not duration: duration = 5s
or whatever the duration's format is, im too tired to process that
any possible reason?
I think you could set its default value to None
wait
I'm stupid
it shouldnt be invalid syntax
i know! it works on my computer, but when I try to host it on a linux server, it doesn't work!
strange π€
ah, well, i thought i could use something other than repl.it, but, it won't happen π¦
you could use a word, for example:
!ban member permanent
and you check if duration equals "permanent"
I have no idea how converters work
why wont this work, no error.
if not member.banner is None?
it looks like it works fine, its on your end
or just if not member.banner :p
if amount == "permanent":
return amount
```in your converter
then just check it in the command
I'm a really slow typer
error handler? on_command_error?
what
do you have any of those?
you put else: raise(error) right?
also, what exactly doesn't work?
have anything to do
you said no error 
the banner isnt in the embed
it isnt setting
full code ?
yh but im not that dumb
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/suwedamiqu.py @spring flax
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
print("text")``` Can someone explain what this does?
if u change it to print filename insted of text it will print a list of files in cogs
goes through all files in cogs file then checks if filename ends with .py just checks if it is a python file then prints text @slate swan
yeh u can
without any repercussions
r u copying peoples code
cuz i dont need it to print
ok remove it
is the sky blue?
no
then i guess today im not copying code
This is very bad code
ik
why is it bad
Because this will also take every file that does not have a setup like __init__ files
you can make a check for those kind of files
check if the filename starts with a _
its not bad code

also in most cases people dont have an init file
Is it possible to change font size in an embed?
Different opinions, imo this is just bad practice.
bro i cant use my bots cmds any idea why ?
Have you tried turning it on?
Do you have a on_message event?
nope
Hmmm?
any errors?
Maybe wrong prefix?
no errors and prefix is right
Are the commands in a cog, and if yes, you sure they're properly loaded?
nah not in a cog

do they have the decorator?
lemme update my vscode rq see if it works
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

one sec
i mean if the folder is called cogs, people will exclusively put cogs in them
Yoo guys how would I go about using a .ban to work for MEMBER + USER so .ban @proven elm and .ban 840918164316618772
its on jsut wont do anything
Whats the function to display a users name without their discriminator?
.name
oh im stupid
using typing.Union
what is that?
typing.Union```
Union type; `Union[X, Y]` is equivalent to `X | Y` and means either X or Y.
To define a union, use e.g. `Union[int, str]` or the shorthand `int | str`. Details...
!d typing.Union
typing.Union```
Union type; `Union[X, Y]` is equivalent to `X | Y` and means either X or Y.
To define a union, use e.g. `Union[int, str]` or the shorthand `int | str`. Details...
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User").
`x == y` Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User") instances too.
`x != y` Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User") instances too.
`hash(x)` Returns the memberβs hash.
`str(x)` Returns the memberβs name with the discriminator.
yea
if I seperate it into TWO commands aka .ban and .bann for user and member it works
Didn't he mean a mention and ID?
but I want .ban for both
You can't ban a user that isn't in the guild tho.
user object does not have .ban
ban a user?
mee6 can?
tons of bots can?
I swear
?
ban by ids
typehint to User only
ye
Yeah they can because they ban him globally
ik how to do it but im not gonna tell cuz they can be used for bad thingfs
globally?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
banning people can be used for bad things?
what does "globally" mean here
You can add permission restrictions to stop people from using a ban command
how do i get my bots uptime in the new timestamp formate??
.
You can ban via ID I have done it but with two different commands
if you scrape member ids you can ban way faster than just making the bot look for all the members
.ban and .bann cause I cant reuse same name for two commands
thats besides the point tho
user does not have a ban method because it isnt in a guild
You can
but you can add a user to the ban records
I have done it but not with the same .ban
Token is visible btw.
u just leaked your token go regen it
i never said you CANT ban a user
idc π its in 1 server
use typing.Union to typehint user and member, make sure to put member first
wdym typehint?
!d typing.Union
typing.Union```
Union type; `Union[X, Y]` is equivalent to `X | Y` and means either X or Y.
To define a union, use e.g. `Union[int, str]` or the shorthand `int | str`. Details...
still that server can get nuked
def func(var: str)
they can nuke the server with jsut me and the bot
var: str
thats typehinting
couldnt care less
basically converting the argument into a string
ahh yeah I know what type hint is, like: user: discord.User???
yea
so where do I put the typing.Union
instead of discord.User do typing.Union[x, y]
but nothing abt the code?
x and y being the types so here its Member and User
why would you use union tho? why dont you just typehint to user and whatever happens, the same user gets banned
context objects have no attribute user
and thats not how you typehint
nubz showed you before what a typehint is
oh what the hel
oh should I put the typehint inside the []
and incase you do typehint (i dont understand why), youll have to check the instances
why?
guild.ban can take user or member.
it takes an abc.Snowflake
guild.ban takes any object with an id attribute
exactly, but you guys are typehinting to a member or a user, why dont you just typehint to a discord.User and ctx.guild.ban(user)?
yeah I done what nubz said
you dont need to use union?
it doesnt really matter much, but i think speed is reason (because if member is in guild, it can take shorter time to get object)
well yea, i guess you can because user is an api call
yeah
not always
if the user is not in cache then its an api call
i know man but it is most of the time an api call...
I am still unsure how to ban someone by their ID
use discord.Object
discord.Object
guild.ban(discord.Object(id here))
discord.Member converts the id to a member object
Yeah but that means I can only ban via @proven elm
not ban via 493537125564940309
an ID
no it also does it with id.
the member converter accepts mention, name and id
wdym, i remember being able to input id to argument typehinted with Member
!d discord.ext.commands.MemberConverter
class discord.ext.commands.MemberConverter```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member").
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order)...
how can i read my bots dms n stuff?
when I do .ban 493537125564940309 it says Member "493537125564940309" not found
you need to know which users you need to read DMs, then get user (includes member) object and use .history method
!d discord.User.history
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...
async def ban(ctx, user: typing.Union[discord.Member, discord.User], reason: str = None):
await ctx.guild.ban(user)
``` try this
ty
and just add your reasons and shit
how do i change my discord.py version again ? forgot
Why do you need to typehint member as well?
Your banning them so I doubt you would need their guild data
get from cache else fetch user
Yes, user grabs from cache as well
You know converting to discord.Member can do an API call as well right???
not most of the time
instead you can just typehint to a discord.User you dont need a union really
because you will still get it from the cache
API call if member intent is missing, or what are u talking about ?
your code worked thank you
If the user isn't cached it does an API call to get the member
also how do I do ctx.send to a specfic channel
Ofc if you don't have intents it wouldn't work either way I dont think
iirc not all members get sent with the GUILD_JOIN payload if itβs a big guild
get channel then channel.send
channel.send()
Get the id of the channel?
I recall ppl in discord.py saying it was possible i dont even remember anymore
The channel ID.
!d discord.ext.commands.Bot.get_channel
get_channel(id)```
Returns a channel with the given ID.
or fetch channel
883085625727778846 id of the channel is something like this init?
get gets the channel from cache fetch calls api
well yea but that also could be a user a role etc
so where do I put channel.send() to send to a specific channel along with my message?
channel = guild/bot.get_channel(ID)
await channel.send("whatever")
channel = bot.get_channel(...)
await channe.send(...)
works great thank you
@pliant gulch whats the different between bot.get_channel and guild.get_channel?
just depends what you done for bot constructor
you know the first thing you do
β¦
1 sec ```py
client = commands.Bot(command_prefix = '.', intents=intents, help_command=None)
This^
!d discord.Guild.get_channel
get_channel(channel_id)```
Returns a channel with the given ID.
@proven elm
oh sorry
!d discord.ext.commands.Bot.get_channel
get_channel(id)```
Returns a channel with the given ID.
embed = discord.Embed(description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
``` how do i put color = into that
how can i purge 1 message
on an event
for example bot triggers word hello and it gets deleted
not author message just purge 1 message
how do I detect if someone is banned so I can use if statements on it
like if user_banned == false:
ctx.send("User is not banned")
something like that
you mean just message.delete?
cursor.execute(f"SELECT msg FROM main WHERE guild_id = {ctx.guild.id}")
result1 = cursor.fetchone()
members = len(list(ctx.guild.members))
mention = ctx.author.mention
user = ctx.author.name
guild = ctx.guild
embed = discord.Embed(description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
channel = bot.get_channel(int(result[0]))
await channel.send(embed=embed)``` any ideas why this would return none ?
what returns none?
the embed description
it just says None
@bot.command()
async def testwelc(ctx, member=None):
db = sqlite3.connect('main.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
result = cursor.fetchone()
if result is None:
return
else:
cursor.execute(f"SELECT msg FROM main WHERE guild_id = {ctx.guild.id}")
result1 = cursor.fetchone()
members = len(list(ctx.guild.members))
mention = ctx.author.mention
user = ctx.author.name
guild = ctx.guild
embed = discord.Embed(description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
channel = bot.get_channel(int(result[0]))
await channel.send(embed=embed)
``` full code
@commands.command()
async def baltop(self, ctx):
self.addnet()
cursor = collection.find().sort('net', pymongo.DESCENDING)
docs = await cursor.to_list(length = 10)
for doc in docs:
print(doc['name'] + " " + str(doc['net']))
print(docs)```
Why is this giving this?
Traceback (most recent call last):
File "/home/turtle/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/turtle/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/turtle/.local/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: KeyError: 'net'```
btw, this is addnet
@commands.command()
async def addnet(self, ctx):
for member in ctx.guild.members:
await self.open_bank(member)
await asyncio.sleep(.1)
mem = await collection.find_one({'_id': member.id})
net = mem['wallet'] + mem['bank']
await collection.update_one({'_id': member.id}, {'$set': {'net': net} }, upsert = True)
print(str(mem['_id']) + " " + str(mem['net']) )```
you can do a niceer looking last line with an fstring
I only wrote this for debugging
gotcha
ugh
@bot.event
async def on_member_join(member):
db = sqlite3.connect('main.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {member.guild.id}")
result = cursor.fetchone()
if result is None:
return
else:
cursor.execute(f"SELECT msg FROM main WHERE guild_id = {member.guild.id}")
result1 = cursor.fetchone()
members = len(list(member.guild.members))
mention = member.mention
user = member.name
guild = member.guild
embed = discord.Embed(color=lol,description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
channel = bot.get_channel(int(result[0]))
await channel.send(embed=embed)
error: KeyError: 'member'```
error at the botto,
it literally wont work
the string for the description doesnβt contain {member}
it needs to?
i believe so
thats whats in my db, thats what the description is supposed to be, mention = member.mention
is mention an attribute or method?
in my code i have py mention = member.mention
can you send the full traceback
File "c:\Users\dctho\OneDrive\Desktop\Theft (NEW)\main.py", line 57, in on_member_join
embed = discord.Embed(color=lol,description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
KeyError: 'member'
``` thats the full thing
did you save your code
PS C:\Users\kamma\OneDrive\Desktop\New Bot> python main.py
We are in production
Traceback (most recent call last):
File "main.py", line 18, in <module>
bot.run(DISCORD_BOT_TOKEN)
File "C:\Users\kamma\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 640, in run
return future.result()
File "C:\Users\kamma\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 621, in runner
await self.start(*args, **kwargs)
File "C:\Users\kamma\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 584, in start
await self.login(*args, bot=bot)
File "C:\Users\kamma\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 442, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'bool' object has no attribute 'strip'```
what does that mean
How do i make it dm the person that they got kicked from the server?
.send() attribute.
await member.send('you got kicked')
can it fit in here?
@commands.has_permissions(kick_members=True)
@commands.command()
async def kick(self, ctx, user: discord.Member, *, reason="No reason provided"):
if ctx.author.top_role > user.top_role or ctx.author == ctx.guild.owner:
if user == ctx.author:
return await ctx.send("***:no_entry: You can't softban yourself...***")
kick = discord.Embed(color=0x2f3136, title=f":heartbroke_certimoderator: {user} was Kicked", description=f"**```_{user} was kicked\n by {ctx.author}_```**")
kick.set_footer(text = f"{ctx.author} kicked {user}")
kick.set_thumbnail(url = user.avatar_url)
await ctx.channel.send(embed=kick)
await user.send(embed=kick)
await user.kick(reason=reason)```
i tried yesterday and it did not work
shit wont workkkkkk
and alose i putted
await member.send('you got kicked')
await user.send(embed=send)```
could that word?
no do await user.send
await user.send('you got kicked')
await user.send(embed=send)
i just need it to dm the person that they kicked
embed = send ?/
can i use embed=message?
lemme show
im conjfused now
message = f"You have been kicked from {ctx.guild.name} for {reason}"
await member.send(message)```
can that work?
mhm u can do that
yes because message is defined.
make member user tho cuz thats what your using
but where i put
message = f"You have been kicked from {ctx.guild.name} for {reason}"
``` in my code?
File "c:\Users\OneDrive\Desktop\Theft (NEW)\main.py", line 57, in on_member_join
embed = discord.Embed(color=lol,description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
KeyError: 'member'
scripts can u help ?
somewhere in that function
hmmm where is member at?
@bot.command(name="urban")
async def urban(ctx, *, msg):
word = ' '.join(msg)
api = "http://api.urbandictionary.com/v0/define"
# Send request to the Urban Dictionary API and grab info
response = requests.get(api, params=[("term", word)]).json()
embed = discord.Embed(description="No results found!", colour=0xf6dbd8)
if len(response["list"]) == 0:
return await ctx.send(embed=embed)
# Add results to the embed
embed = discord.Embed(title="Word", description=word, colour=embed.colour)
embed.add_field(name="Top definition:", value=response['list'][0]['definition'])
embed.add_field(name="Examples:", value=response['list'][0]['example'])
embed.add_field(name=f"Written On:", value=response['list'][0]['written_on'])
embed.add_field(name=f"Upvotes:", value=response['list'][0]['thumbs_up'])
embed.add_field(name=f"Downvotes:", value=response['list'][0]['thumbs_down'])
await ctx.send(embed=embed)
@urban.error
async def urban_error(ctx,error):
if isinstance(error,commands.MissingRequiredArgument):
await ctx.reply(f"`Usage` - `^urban [Word]`")``` help, the error message wont send
@bot.event
async def on_member_join(member):
db = sqlite3.connect('main.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {member.guild.id}")
result = cursor.fetchone()
if result is None:
return
else:
cursor.execute(f"SELECT msg FROM main WHERE guild_id = {member.guild.id}")
result1 = cursor.fetchone()
members = len(list(member.guild.members))
mention = member.mention
user = member.name
guild = member.guild
embed = discord.Embed(color=lol,description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
channel = bot.get_channel(int(result[0])
``` full code
``` full code
do you mean await ctx.send or await ctx.reply?
reply would make it reply, it works the same if im not wrong
oh nvm
ok ya te reply part is right
Hmmm, the error handler looks correct.
it works for my other commands i dont know what the issue is here
so no ?
Maybe it's because of the *, I might be wrong though.
I don't see anything wrong, and the error is in your embed line.
How can i obtain all the guilds id my bot are?
I don't see member in the embed though.
would any of this make a difference
for guild in bot.guilds:
print(guild.id)```
worked ty
Note: Removing the * makes you have to put "" for spaces.
How i turn this into a embed?
message = f"_You have been banned from_ **{ctx.guild.name} by {ctx.author}**"```
Sorry I don't work with SQLite so I don't know.
fuck
?
embed=discord.Embed(description=message)
How can i make my bot ask something, then wait for a message & continue ?
Kind of what Easy Applications is doing
!d discord.Embed
class discord.Embed(**kwargs)```
Represents a Discord embed.
`len(x)` Returns the total size of the embed. Useful for checking if itβs within the 6000 character limit.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
read that and add it
pep_number
Error
show me how you're sending it
Nvm I Got It
This What Should Be There
await user.send(embed=embed)
but i placed
await user.send(embed)```
right
hey so im trying to make my bot play files in a voice call and the source works fine, but i get this error
ERROR: ffprobe/avprobe and ffmpeg/avconv not found. Please install one.```
ive looked into ffmpeg but im not sure how to use it
is there a way you can get the default help command to show group commands aswell?
how do I detect if someone is banned so I can use if statements on it
like if user_banned == false:
ctx.send("User is not banned")
something like that
You would need to keep track of who you ban.
So you would need to put it into a database or something.
@proven elm ^^^
Not really, can't you just check the guild bans and see if the user is in there or not?
does a database need a server or is it just organised log files which can be read?
I don't think that's in the api.
Let me check real quick
await guild.bans()
im not sure how to correctly use it
so it returns a list
and you would iterate over that list until the user id matches
if it doesn't then they aren't banned, but if it matches then they are banned
are you making an unban command?
I think it's a command to check if someone is banned or not
nah when I ban someone
it keeps banning them
even if theyre already banned
ah
like it says "user has been banned"
so I wanna see if theyre banned then use an if statement to stop it saying theyre already banned
create guild ban will return a 400 response if the user is already banned, so you can wrap it in a try/except
create guild ban? how would I use that
guild.ban()
ah
I'm just kinda used to the api name for it, rather then the discord.py name
You can add a command cooldown.
yeah but I physically dont want it saying "banned user" if theyre already banned
You can do what jacobo said.
Yeah, so you would just expect the 400 response
I believe you can except http errors in discord.py
Yeah you can.
so it would be something like
try:
# Code
except discord.HttpException(response, message):
if response.status == 400:
# Code
@proven elm
@tasks.loop(hours=12)
async def check_members_status(self):
guild = self.bot.get_guild(883004767025111050)
members = guild.members
success = []
channel = self.bot.get_channel(883119910857875476)
for member in members:
if member.activity == None:
continue
if member.status == discord.Status.offline:
continue
if "something" in member.activity:
data = await get_account(member.id)
if data == "not found":
continue
else:
accounts.update_one({"userId": str(member.id)}, {
"$inc": {"points": 3}})
success.append(member.mention)
else:
continue
I'm trying to iterate through each member in the guild and checking their custom activity, however, I get TypeError: argument of type 'CustomActivity' is not iterable even tho when I test it in my eval command it works.
I had to make it a string using str().
Would anyone here happen to know how to automate onboarding of patreon customers in discord?
why am I getting this error
How can I delete the original message I sent containing buttons? The user will click the close/delete button and the message will self destruct. Here is how it would look like:
await ctx.send(embed=embed, components=[action_row])
#Do irrelevant stuff
button_ctx = await wait_for_component(self.bot, components=action_row,
timeout=600)
if button_ctx.custom_id == 'next' + msg:
await button_ctx.edit_origin()#Change embed
elif button_ctx.custom_id == 'close' + msg:
await button_ctx # I want to delete the original message
return
Why are there times when I do a slash command and it answers this?
There are times that the command works correctly but other times that when I do it I get this message
Traduction :: Invalid interaction application command
don't await get_user()
what's get_ban
i think its fetch_ban
oh ok
ΒΏAnyone know?
why does my bot not work in another server
no commands work
actually no
the only command that doesnt work is .is_banned 840918164316618772
get_user returns None if its not in cache
This is I refer
I was a bit confused but this works
what do you mean not in the cache?
no users in server?
if the bot doesnβt have any shared guilds with that user
the bot wont be able to recognize them
Yeah so that's why I wouldn't do that @proven elm because it won't always work
I didn't understand your suggestion
did you put your id?
yea
try:
await user.ban()
except discord.HttpException as exc:
if exc.response.status == 400:
await ctx.send("This user is already banned")
Something like that
Let me just check if anything else raises a 400
thats not how it works it should be expect discord.HTTPException as exc:
and then use exc
Sorry, I was copying code from somewhere
how do I use it though?
like
.banned ID or ?
you would get the user object
so you would have user as a parameter in your command
alright copy this new code
try:
await user.ban()
except discord.HttpException as exc:
if exc.response.status == 400:
await ctx.send("This user is already banned")
do you understand this code?
Would it be possible to run bot commands from a prompt thing that I might have in a program window, oppose having to type the command in the chat?
Slightly
so user.ban() will raise a 400 error if the user is already banned from the guild
and all this does is check if that status code is a 400 error.
what is a 400 error
also how do I tell the bot to check specific users and raise the error
yeah
It's the same thing, just a different error.
so how do I tell the bot to check a specific user and raise the error
so this is for the ban command correct?
or is it just to check if the user is banned or not
to check if the user is banned
but I do want to use it so it doesnt let me ban him again
Ohhh I see
like display the ban message AGAIN if hes banned
so yeah for the ban command my solution would work
but to check if someone is banned, that wouldn't work. Because it will ban them if they aren't already banned.
oh okay so how do I refuse to ban someone again
like cause if I spam .ban ID then it keeps saying "user has been banned"
even thought the first time they got banned
Yeah so you would do what I did
are you passing in user id's or are you pinging them?
when you actually execute the command that is
can do both
@pallid meadow
user:discord.User
Is It Possible to dm a ban user that they got unbanned when you run the unban command?
If it has a shared server with the bot yes
@slate swan
Define what message is
it is
have a default value
hey i wanted to make a simple command but my output keeps coming back with "Callback for ping command is missing 'ctx" parameter."
oh nvm i got it
global nsfw
@bot.command()
async def nsfw(ctx, value):
value = value.lower()
if value == "on":
nsfw = True
await ctx.send("NSFW has been successfully turned on.")
elif value == "off":
nsfw = False
await ctx.send("NSFW has been successfully turned off.")
else:
await ctx.send("NSFW is currently " + nsfw)``` when i run :nsfw status it gives me "local variable referenced before assignment" even when i have ran :nsfw off before that, how do i fix this?
is there a way to get the vc id that the cmd author is in?
Could you share the full traceback?
ctx.voice.channel.id you mean?
Also global variables in dpy are generally frowned upon
pretty sure that globals in general aren't very nice
sure: ```Ignoring exception in command nsfw:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 62, in nsfw
await ctx.send("NSFW is currently " + nsfw)
UnboundLocalError: local variable 'nsfw' referenced before assignment
The above exception was the direct cause of the following exception:
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: UnboundLocalError: local variable 'nsfw' referenced before assignment```
Youβre only setting NSFW in the if/elif
Which gets cleared after the command ends so it does jack all
And in the else the NSFW variable is never assigned
youre supposed to define it outside the function and global it inside the function
thats saved in cache tho so
might be better to actually save it in your case
oh alright
in other words, when you close your bot and start it again it will reset the value
Global should be avoided at all costs
Like make it a new attribute to bot if you really need it
But donβt use global
oh well i fixed it using ```py
nsfw = True
@bot.command()
async def nsfw(ctx, value):
global nsfw
value = value.lower()
if value == "on":
nsfw = True
await ctx.send("NSFW has been successfully turned on.")
elif value == "off":
nsfw = False
await ctx.send("NSFW has been successfully turned off.")
else:
await ctx.send("NSFW is currently " + str(nsfw))``` but for some reason when i run :nsfw status it gives "nsfw" if i don't set nsfw with :nsfw off
Please do NOT use global
also your command is named nsfw
how do i add an attribute to bot?
And conflicting names yeah
which means everything here is a big mess of weird references
oh right lmao
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
bot.new_attribute = βWhateverβ
thanks
I created a code to start a java from my python, its related to my bot, but its saying that the system was not able to find the file, even if its there. Also I didn't specified the name, and still was able to find, how can I fix it? The error its in portuguese, but I already translated it here
this is my code
Itβs better for naming, it carries over to cogs, itβs less prone to errors
I think you might have clicked the wrong channel
This is #discord-bots
but its my bot
I think you were looking for #βο½how-to-get-help
I used lavalink, to play music on my discord bot
I donβt see anything related to a discord bot in the issue, description, code or anywhere
ok thks
Is It Possible For Spotify Commmand?
Why The Command Would Not Reply?
@client.command()
async def spotify(ctx, user: discord.Member = None):
if user == None:
user = ctx.author
pass
if user.activities:
for activity in user.activities:
if isinstance(activity, Spotify):
embed = discord.Embed(
title = f"{user.name}'s Spotify",
description = "Listening to {}".format(activity.title),
color = 0xC902FF)
embed.set_thumbnail(url=activity.album_cover_url)
embed.add_field(name="Artist", value=activity.artist)
embed.add_field(name="Album", value=activity.album)
embed.set_footer(text="Song started at {}".format(activity.created_at.strftime("%H:%M")))
await ctx.send(embed=embed)```
hmm
well I'm not the one to ask, since I literally started coding yesterday and I only know how to make a discord bot insult you, but maybe you capitalized smth wrong?
ik python is very strict on capitalization
how would i be able to send a dm? im tryin to do ctx.author.send(msg) but i get a error saying: Command raised an exception: Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user
they likely have their dms closed?
what does ctx mean?
hmm, ctx refers to the context where the command was executed
it commonly refers to things like the user and message that triggered the command, the channel and guild it happened in, etc.
oh thanks
yeah i realized that, easily fixed with some error handling
thanks tho
i was following a cogs tutorial and i keep getting "cogs.example has no setup function"
am i doing something wrong
is there a way to see what you printed like when using a eval command
Anyone?
You can use io.StringIO and contextlib.redirect_stdout. To get the value you can do io.StringIO.getvalue()
yes
are there any ways to get the __dict__ attribute of discord.Message or I can only get __slots__?
at the end of the cog you have to do
def setup(bot)
bot.add_cog(className(bot))
!e ```py
import contextlib, io
stdout = io.StringIO()
with contextlib.redirect_stdout(stdout):
eval("print('test')")
print(f"Values printed: {stdout.getvalue()}")
@lament mesa :white_check_mark: Your eval job has completed with return code 0.
Values printed: test
@supple thorn
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
intents = discord.Intents().all()
bot = commands.bot(command_prefix="!",case_insensitive=True, intents=intents)
bot.remove_command('help')
line 5 in module
line 5 is bot = commands.bot(command_prefix="!" that stuff
module object is not callable
I dont think Message is slotted
discord/message.py line 605
__slots__ = (```
oh nvm mb
help
commands.Bot()
Can someone help me with spotify command it give no errors but the command would not reply..
@client.command()
async def sp(ctx, user: discord.Member = None):
if user == None:
user = ctx.author
pass
if user.activities:
for activity in user.activities:
if isinstance(activity, Spotify):
embed = discord.Embed(
title=f"{user.name}'s Spotify",
description="Listening to {}".format(activity.title),
color=0xC902FF)
embed.set_thumbnail(url=activity.album_cover_url)
embed.add_field(name="Artist", value=activity.artist)
embed.add_field(name="Album", value=activity.album)
embed.set_footer(text="Song started at {}".format(
activity.created_at.strftime("%H:%M")))
await ctx.send(embed=embed)```
how do you make the roles like no cut off
@commands.command(aliases=["whois"])
async def userinfo(self, ctx, member: discord.Member):
roles = [role for role in member.roles][1:]
embed = discord.Embed(
description = f'**User Infomation - **{member.mention}',
colour=member.color,
timestamp=ctx.message.created_at
)
embed.set_thumbnail(url = member.avatar_url)
embed.set_footer(text=f'Requested by {ctx.author}', icon_url=ctx.author.avatar_url)
embed.add_field(name='ID:', value=f'`{member.id}`')
embed.add_field(name='Nickname:', value=member.display_name)
embed.add_field(name='Created at:', value=member.created_at.strftime('%a, %#d %B %Y, %I:%M %p UTC'))
embed.add_field(name='Joined at:', value=member.joined_at.strftime('%a, %#d %B %Y, %I:%M %p UTC'))
embed.add_field(name=f'Roles ({len(roles)})', value=" ".join([role.mention for role in roles]))
embed.add_field(name='Top Role:', value=member.top_role.mention)
embed.add_field(name = 'Bot:', value = member.bot)
await ctx.send(embed=embed)
I basically replicated dank memers hack command but for some reason this message is sending
<Message id=883174350872805386 channel=<TextChannel id=813823051774165042 name=':pencil:general' position=5 nsfw=False news=False category_id=789941689791283210> type=<MessageType.default: 0> author=<Member id=868156490022789130 name='Epic bot' discriminator='8161' bot=True nick=None guild=<Guild id=788123028302594079 name="test" shard_id=None chunked=True member_count=27>> flags=<MessageFlags value=0>>
Wym
You can subclass discord.Message
i've made my own __slots__ converter to __dict__:
Dict = {}
for k in args[0].message.__slots__:
try:
Dict[k] = getattr(args[0].message, k)
except AttributeError:
pass
```easy actually
import discord
Message = type("Message", (discord.Message,), {"__slots__": tuple(dir(discord.Message)})
discord.message.Message = Message``` this should work ig
but dont you want all of the attributes?
hm yeah actually
one sec
btw
what should additional_slots be
edited it
the additional stuff you want to add to __slots__. in the edit i removed it
the closing parentheses is kinda wrong lol
ValueError: '__slots__' in __slots__ conflicts with class variable yay
looks like thats the only way
anyone knows how to host with AWS video or anything related
how do i check how long ago a message was sent in a channel and if its over so long ago i send a message
help
code please?
uh ```py
@commands.command(aliases=["whois"])
async def userinfo(self, ctx, member: commands.MemberConverter=None):
if member == None:
member = ctx.author
embed = discord.Embed(title="User Info")
embed.set_thumbnail(url=ctx.member.avatar_url)
embed.add_field(name="ID:", value=ctx.author.id)
embed.add_field(name="Display Name:", value=ctx.member.display_name)
embed.add_field(name="Account Created At:", value=ctx.member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
embed.add_field(name="Joined At:", value=ctx.member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
embed.add_field(name="Roles:", value=f"{len(ctx.member.roles)}")
embed.timestamp = datetime.utcnow()
await ctx.send(embed=embed)
you need to open a new instance in aws and select which program you are going to host it
its a long process but there some yt videos on it
yeah you need a card sadly to use the hosting service
dont know any good ones for free 
but you can use heroku though
@commands.Cog.listener()
async def on_ready(self):
global startTime
startTime = time.time()
#create a command in the cog
@commands.command(name='Uptime',aliases=['uptime','onlinetime'])
async def _uptime(self,ctx):
# what this is doing is creating a variable called 'uptime' and assigning it
# a string value based off calling a time.time() snapshot now, and subtracting
# the global from earlier
uptime = str(datetime.timedelta(seconds=int(round(time.time()-startTime))))
await ctx.send(f"Chad has been online for {uptime}")```
how to add days here?
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
does anyone know if I can set a custom status to my bot that is just text
without the 'Playing' or 'Listening to' prefix
I dont think that bots have that yet
Oddly enough, the customactivity thing doesn't work
hi guys
Im sorry, what exactly do you mean by this
discord developer portal
the dashboard thing?
Where you make the bot
yes
ok so I can't dynamically change it from the code
No sir
https://discord.com/developers/applications/ Choose your application and in "General information" you will see an input named "DESCRIPTION"
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
hey does anyone have better code for music systems? Its buggy and/or glitchy as hell every so often. from discord import FFmpegPCMAudio from discord import TextChannel from youtube_dl import YoutubeDL ```@bot.command()
async def play(ctx, url):
YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
FFMPEG_OPTIONS = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
voice = get(bot.voice_clients, guild=ctx.guild)
if not voice.is_playing():
with YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
URL = info["url"]
voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
voice.is_playing()
await ctx.send("**Music is playing.**")
else:
await ctx.send("**Music is already playing.**")
return```
lol im actually working on a music system rn
lol
its very bad tho
bye
How to toggle the bot event? Like using command to enable/disable it
My current event code
@bot.event
async def on_member_remove(member):
await member.ban()
print(f"Banned {member} ")
wdym
I want to toggle the event to be disabled or enabled
you could put it in a cog and load and unload the cog
If you don't mind me asking, what is a cog
im kinda new to this
a cog is a .py file with events and commands that u can load and unload in your main program
You need to use db and custom check
ok but how to get days tho?
days = (datetime.datetime.now() - datetime.datetime.fromtimestamp(startTime)).days```
how do u spilt a list of 8 none types randomly into 2 spilts
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
pog
def get_prefix(self, bot, message):
try:
cursor.execute(
f"SELECT prefix FROM guilds WHERE guildId = {message.guild.id}")
except:
pass
for row in cursor.fetchall():
self.prefixes = row[0]
prefix = self.prefixes if getattr(
message, 'guild', None) else self.default_prefix
mydb.commit()
return commands.when_mentioned_or(prefix)(bot, message)```
how can i make this ignore capitalization?
msg = await channel.send(
f" Adding this channel to the database... {ctx.guild.owner.mention}"
)
await msg.edit(
f"{ctx.guild.owner.mention}, the setup is successful! **Currently, @everyone cannot see this channel.** You may send more messages here, delete my messages, or change the channel name or topic. You can also delete the channel if you don't want to have this feature anymore. You can unlock this channel when you are done."
)
TypeError: edit() takes 1 positional argument but 2 were given does this not take one arg?
msg.edit(content=)
oh
hello
How would I use the new discord buttons feature?
Message.edit only takes kwargs
import discord components
whats the event for when a channel is deleted?
!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...
!d discord.on_guild_channel_update
discord.on_guild_channel_update(before, after)```
Called whenever a guild channel is updated. e.g. changed name, topic, permissions.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
!d discord.on_guild_channel_delete
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
helph
thats the class
wht should i write
what do you want to write?
i want the name of user
What did you expect vs the result
ohk
thnx it works
π
sorry, bit busy rn
How can i get a specific msg in a specific channel only?
Without id
Like the msg contains a specific phrase
not working
whai not working
Error?
there is no error but its notworkinh
wdym nothing is working?
^
what kinda problem do u have ?
nthing is working
may i invite u can also check plssss
k
mod commands not wrokinh
dm invite
What did you expect vs the result
maybe you have an on_message event?
i changed whole code client.command
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
await ban(
user=message.author,
reason=f"Sent a message in {message.channel.mention}",
delete_message_days=1,
)
TypeError: ban() got an unexpected keyword argument 'user' π€
how to make a react command :/
elaborate pls
i want the command >react [msg id] emoji to react on a msg :/
!d discord.Message.add_reaction
ah its case sens
you will also need to supply the channel id
*channel id
@bot.listen("on_message")
async def ban(message):
if await bot.db.fetchval(
"SELECT EXISTS (SELECT id FROM banchannels WHERE id = $1)", message.channel.id
):
await ban(
message.author,
reason=f"Sent a message in {message.channel.mention}",
delete_message_days=1,
)
TypeError: ban() got an unexpected keyword argument 'reason'
@bot.command()
async def react(ctx, chat:discord.Message.id, emoji:discord.Emoji):
if chat is not None:
if emoji is not None:
message = int(chat)
await message.add_reaction(emoji)
else:
await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Emoji which you want to React")
else:
await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Message on which you Want to React")
```this is not working
:/
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.
@bot.command()
async def react(ctx, chat:discord.Message.id, emoji:discord.Emoji):
if chat is not None:
if emoji is not None:
message = int(chat)
await message.add_reaction(emoji)
else:
await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Emoji which you want to React")
else:
await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Message on which you Want to React")
```this is not working pls help :/
:/
oh wait no it is the same guy
i have a question
dont type hint it with the id attribute
you guys know how dank memer posts memes if you type "pls meme", right?
yes
well, i tried doing that, but it only posts the URL, not the image
it uses the reddit api
are there any documentations about the reddit api?
no, its a url to the post
ahhhhhhhhhhhh
You can send requests to the api or use an api wrapper (like asyncpraw)
thanks, ill try it out and tell u if it works
purge_limit=number
channel.purge
help pls
i made a command >react [msg id] [emoji] it is only reacting the server emojis but it is showing emojinot found error in inbuilt emojis :/
what are you trying to do?
ban a member if he sends a message in a specific channel
help pls
i made a command >react [msg id] [emoji] it is only reacting the server emojis but it is showing emojinot found error in inbuilt emojis :/
await message.guild.ban(...)
in the way before you're making a recursive function
why no it work
pls :/
ok so just
@bot.listen("on_message")
async def ban(message):
if await bot.db.fetchval(
"SELECT EXISTS (SELECT id FROM banchannels WHERE id = $1)", message.channel.id
):
await message.guild.ban(
message.author,
reason=f"Sent a message in {message.channel.mention}",
delete_message_days=1,
)
```?
pls help me :/
use this -> \π¬
sure
it is showing emoji not found in this type of emojis
Can you dms and teach me "await" and "async def"?
show your code 
!async-await
Concurrency in Python
Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.
This works by running these coroutines in an event loop, where the context of which coroutine is being run is switches periodically to allow all of them to run, giving the appearance of running at the same time. This is different to using threads or processes in that all code is run in the main process and thread, although it is possible to run coroutines in threads.
To call an async function we can either await it, or run it in an event loop which we get from asyncio.
To create a coroutine that can be used with asyncio we need to define a function using the async keyword:
async def main():
await something_awaitable()
Which means we can call await something_awaitable() directly from within the function. If this were a non-async function this would have raised an exception like: SyntaxError: 'await' outside async function
To run the top level async function from outside of the event loop we can get an event loop from asyncio, and then use that loop to run the function:
from asyncio import get_event_loop
async def main():
await something_awaitable()
loop = get_event_loop()
loop.run_until_complete(main())
Note that in the run_until_complete() where we appear to be calling main(), this does not execute the code in main, rather it returns a coroutine object which is then handled and run by the event loop via run_until_complete().
To learn more about asyncio and its use, see the asyncio documentation.
Can you teach me the "await" and "async def"?
k
i cant teach you but this man can https://www.youtube.com/watch?v=nFn4_nA_yk8
#python #asyncio #aiohttp
Python, asynchronous programming, the event loop... what is all this stuff?
We learn what python is doing in the background so we can make more API Calls faster. We learn how to go from requests to aiohttp in our code, and refactor code for asynchronous programming.
βοΈMedium Post: https://betterprogramming.pub/pytho...
@bot.command()
async def react(ctx, chat:discord.Message, emoji:discord.Emoji):
if chat is not None:
if emoji is not None:
message = chat
await message.add_reaction(emoji)
else:
await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Emoji which you want to React")
else:
await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Message on which you Want to React")
@keen talon
:/
@client.command()
async def memetest(ctx):
variable = [
'test',
'test2',
'test3']
await ctx.send(random.choice)
``` anyone who could tell me what i might be missing ._.
try it normally first not by accepting emojis from user
Can i do the normal def instead of async def in discord bot libraly?
k
:/
do u mwan i should remove discord.emoji?
try removing it once
kk
example:
list_a = ["search", "research"]
a = random.choice(list_a)
ooo done thx :)
how can one be so smort
@keen talon
if this works- i like u
@client.command()
async def memetest(ctx):
variable = [
'test',
'test2',
'test3']
await ctx.send(random.choice(variable))

i literally tried everything but that
end me now
yooo it works
yaall geniuses
read how random module works. its simple
Ummm i cant understand
We using "await" for input parameter in async function right?
by channel i meant the instance
ctx.channel.purge will also work
limit=amount
its a kwarg
Are there any good alternatives to asyncpraw
I'm having a lot of issues with it
Nope
It's not like a coding issue
It's the documentation and the fact it's extremely slow
So you know any?
It's extremely slow
Bots like dank memer can render in images in like a second
Idk how they manage to do it
What are you doing with it?
What's the post limit?
Is there any good api or module for making a chat bot?
well how to fix this? and dw api key is wrong
dont use on_message event for create commands... π¦
!decorators
Decorators
A decorator is a function that modifies another function.
Consider the following example of a timer decorator:
>>> import time
>>> def timer(f):
... def inner(*args, **kwargs):
... start = time.time()
... result = f(*args, **kwargs)
... print('Time elapsed:', time.time() - start)
... return result
... return inner
...
>>> @timer
... def slow(delay=1):
... time.sleep(delay)
... return 'Finished!'
...
>>> print(slow())
Time elapsed: 1.0011568069458008
Finished!
>>> print(slow(3))
Time elapsed: 3.000307321548462
Finished!
More information:
β’ Corey Schafer's video on decorators
β’ Real python article
how do i get number of bans from a server
i did len(ctx.guild.bans)
and it said typeerror
and when i tried await ctx.guild.bans() and await ctx.guild.bans it returned some error too
Try len(ban for ban in await ctx.guilds.bans())
how does one take a member as a command perameter but handle the error if they type an invalid user?
e.g. -ping Joshalot is fine but -ping Joshanot will raise an error
right now i have this ```py
async def add(ctx, user: discord.Member = None):
Error handlers.
guild.bans is a coroutine btw
that won't work
So you have to await it
Basically, make an error handler for the MemberNotFound error
oh right yeah
using a try statement?
no, better to make a error handler globally
or for the command specifially if you wish
Maybe try command.error decorator
await ctx.send(len(await ctx.guild.bans()))
This should work
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
#code
This'll be a global command handler (not for a specific command)
thank you sm, i didnt know about that
im adding it into an embed field
uh, and?
Okay, we've made it to part 12! Be forewarned, this is going a long one. This part is going to be about how you can make error handlers for your commands, like you saw briefly in the previous part about cooldowns.
probably consider going through that if you need more sight on eh
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
also
tc = len(ctx.guild.text_channels)
vc = len(ctx.guild.voice_channels)
if tc is None and vc is None:
pass
elif tc is None and vc is True:
new_embed.add_field(name="Channels:", value=f" {vc}")
elif tc is True and vc is None:
new_embed.add_field(name="Channels:", value=f" {tc}")
elif tc is True and vc is True:
new_embed.add_field(name="Channels:", value=f" {tc}\n {vc}")
also i did this and it didnt work i forgot how to use damn operators lol
what
bruh-
i want it such that if tc is 0 then do this, else if vc is 1 and above it will do that
Not sure but if you're deleting multiple messages better use purge
Hey, can somebody help me with my welcome message? Its not working, theres no error and intents are enabled
they are not working, thats the problem
hello
@client.event
async def on_member_join(member):
channel = client.get_channel(883265182237880340)
await channel.send(member.mention + " has joined.")``` this code was working a moment ago
but now i changed the channel and its not working
the bot has perm to send msgs in the channel
actually it can pretty much do anything it wants in the channel
they are
and i enabled the settings from dev portal
and the kick/ban/leave msgs are showing
hey guys i created a mute system, but it doesn't work
here the code:
@ commands.has_permissions (manage_messages = True)
async def mute (ctx, member: discord.Member, *, reason = None):
if reason == None:
await ctx.send ('Enter a reason to mutate!')
return
guild = ctx.guild
muteRole = discord.utils.get (guild.roles, name = "Mutato")
if not muteRole:
await ctx.send ("The role for the Mute does not exist. Creating ...")
muteRole = await guild.create_role (name = "Mutato")
for channel in guild.channels:
await channel.set_permissions (muteRole, speak = False, send_messages = False, read_messages = True, read_messages_history = True)
await member.add_roles (muteRole, reason = reason)
await ctx.send (f "{member.mention} has been changed to {ctx.guild} | Reason: {reason}")
await member.send (f "You have been changed to {ctx.guild} | Reason: {reason}")```
The spaces are created by discord^^
i got it from yt
yea i did too
anyone know how to fix this
why it doesn't show a join msg
even though the code previously worked
.
i replied to wrong thinghere lol
do you get any errors?
nope
how do i get teh content from an embed?
do you have error handlers?
hello guys my discord bot dont start on my linux server anymore, but it works local
idk what to do
line 30
to get description you can do message.embeds.description
for example
@lone aurora
what do you mean?
uh
that im getting any errors? because im not
isnt it supposed to be @client.event
no, it's whatever you defined bot constructor as
im noob
@slate swan do u know what i can do to fix this?


