#discord-bots
1 messages · Page 441 of 1
is :trash: a custom emoji?
the & sign
vote is not defined
please help
whats vote
then replace :trash: with <name:id> of the custom emoji
see now
it was smth of my own
need some help^^^
well i wouldnt copy, it just didnt make sense. let me try it
await message.add_reaction('')
def check(reaction, user):
return reaction.message == message and str(
reaction.emoji) == '' and user == ctx.author
await self.bot.wait_for('reaction_add', check=check)
await message.delete()```
oh wait
discord.Message doesnt have __eq__
That means you cant compare 2 Message objects
compare ids
Do reaction.message.id == message.id
k
Can you send a embed to user dms
why not?
Oh
this is a DM
Oh okay thanks
@client.event
async def on_user_update(before, after):
print(f'{before} has updated his account information!')
if before.display_name != after.display_name:
print()``` How do I make it so it shows what information has changed about the user?
cause right now it tells me "user has updated his account information"
but how do I see what changed
that is for nicknames
so you should be doing on_member_update
I have both
and since before and after are member objects, they too would have the dispaly_name or mention attr
@client.event
async def on_user_update(before, after):
print(f'{before} has updated his account information!')``` so how do I print the display_name before and after
for member
Anyone know why line 44 indentation isn't right?
@client.event
async def on_user_update(before, after):
if before.display_name != after.display_name:
print(f"{member.mention} has updated their username, from {before.display-name} to {after.display_name}!")
damnnnn thankk you
what happends when discord.py ends?
You can try using waiting for maintenanced forks
will it still work when the api updates?
Like there's already edpy, hikari, etc.
dpy library will be ceased, you'll have to find other libraries/forks
oh ok
missing 1 required positional argument: 'after'
i am obliged to ask waht theme this is
do you not like it?
is there a way for a bot to be able to change the name of guild owner?
i love it that's why i'm asking
ahaha lemme get it for you
these are my extensions
pretty sure its rainbow brackets and monokai pro
and also material icons theme
lovely tyty
anyone?
no bot's cannot change the guild owners nickname
fields = [("Owner", ctx.guild.owner, True),
Does anyone know why ctx.guild.owner is returning none?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: search() got an unexpected keyword argument 'num'
@raven peak
async def find(ctx,*, query):
author = ctx.author.mention
await ctx.channel.send(f"Here are the links related to your question {author} !")
async with ctx.typing():
for j in search(query, num=10, stop=10, pause=2):
await ctx.send(f"\n👉 {j}")
help pls
!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.
@bot.event
async def on_message(message):
try:
if message.mentions[0] == bot.user:
db = sqlite3.connect('main.sqlite')
cursor = db.cursor()
cursor.execute(f'SELECT prefixes FROM main WHERE = {message.guild.id}')
result1 = cursor.fetchone()
await message.send(f'The prefix is {result1[0]}')
except:
pass
await bot.process_commands(message)
raise TypeError command_prefix must be plain string, iterable of strings, or callable returning either of , not NoneType
btw you put await message.send
what is the code for your command_prefix = ...?
Hold on
I think I know
When I’m creating the table how would I make something an int
Cause right now I’m setting one of the values to a text string even tho it’s s channel I’d
what doespy pass_context=Truedo
it is outdated
Could I do int for a value in my table
wait who's this for 😆
how to get bot username and tag python
I think I know my error
cursor.execute('SELECT prefixes FROM main WHERE = ?, (message.guild.id)')
``` this doesn't really change anything now, but in case you put this similar code to a `insert` statement, use the above (don't use f strings)@slate swan
it was for what you asked about pass_context
ok
Thanks for ur help
if it is for a command
ctx.me.name and ctx.me.discriminator
Or you can do str(ctx.me)
oh okay thanks, its cause someone replied to it so i got a bit confused
is it true that discord.py is gonna end or
@spring flax plz help
development on that has already stopped
can anyone help me in creating a google search cmd ?
it does not mean you can't use it now, but in 2022 you would need to switch
anyone?
!d discord.TextChannel.category
category```
The category this channel belongs to.
If there is no category then this is `None`.
i wanna check that the channel is in a chosen category or not
so many bots are gonna have to switch damn
no its for terminal
like: py print("logged into:" )
and then the username
okay yeah so
@spring flax^
?
Dude he just showed @hoary gust
is that for checking that is it in a category or for checking that it is in which category
.
^
local variable 'voice_channel' referenced before assignment
The category the channel belongs to.
can any one tell me? why tho
ok thanks but how to use it, i mean how can i check
it says it on the docs.
print(f"{bot.user.name}#{bot.user.discriminator}")```
@peak rune
thank you.
@spring flax how long have u been coding
any help
Send code
why?
Which line did the error appear
Just a question
hey guys how can i check the category, an simple example will be more helpful
!d discord.TextChannel.category
category```
The category this channel belongs to.
If there is no category then this is `None`.
but how can i check?
Bruh
.....?
thats the problem
Wym check bro?
async def example(ctx, channel:discord.TextChannel):
await ctx.send(channel.category)
this would return the category of which the channel you specified falls under
i know many languages
BTW did u know, not only discord.py but Python itself tries to convert the parameters to the same class it's typehinted to
any help
how do i get/count a role mentioned in a specific channel's msgs?
python
!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.
``Ignoring exception in command join:
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 "/home/runner/bestbot/cogs/music.py", line 16, in join
await voice_channel.connect()
UnboundLocalError: local variable 'voice_channel' 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 'voice_channel' referenced before assignment``
Loop through all the messages and add a check to see if role.mention in message.content
here anysolution
@waxen granite
CREATE TABLE IF NOT EXISTS main(
guild_id TEXT,
loggingchannel INT,
loggingstatus TEXT,
pingableroles INT,
prefixes TEXT
)
''')
will this work
But it will count as api abuse anyways
Hi,
I was wondering if those dynamic timestamps were possible using discord.py
(dynamic timestamps are the things like <t:1630609200:R> and <t:1630609200:f>)
Indeed
code?
i mean like
category = discord.utils.get(member.guild.categories, name='Verification-Logger')
log = discord.utils.get(channels, name="zenesis-verification-logger")
if logs in category:
pass
if logs not in category:
log = await member.guild.create_text_channel("Zenesis-Verification-Logger", category=category)
will it work @maiden fable
?
!d discord.CategoryChannel.channels
channels```
Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels.
category.channels bro
How do you do it?
I can't find it on google or the docs, all it shows is standard timestamps
any fix
Just like u do it normally? Get the unix time and do <t:timestamp:R>
can't help without you sending the code here
``import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("You're not in the a voice channel!")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
ctx.voice_client.move_to(voice_channel)
@commands.command(aliases=['leave', 'l'])
async def disconnect(self, ctx):
await ctx.voice_client.disconnect()
@commands.command(aliases=['p'])
async def play(self, ctx, url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed1 1 -reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format':'bestaudio'}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['format'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
@commands.command()
async def pause(self, ctx):
await ctx.voice_client.pause()
await ctx.send('✨Paused ⏸️')
@commands.command(aliases=['r'])
async def resume(self, ctx):
await ctx.voice_client.pause()
await ctx.send('✨Resumed >')
def setup(bot):
bot.add_cog(music(bot)) ``
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)
Is there a module to convert to the unix time so it can be done automatically?
BRO I HATE MYSELF
LMAO
!d time.time
time.time() → float```
Return the time in seconds since the [epoch](https://docs.python.org/3.10/library/time.html#epoch) as a floating point number. The specific date of the epoch and the handling of [leap seconds](https://en.wikipedia.org/wiki/Leap_second) is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. This is commonly referred to as [Unix time](https://en.wikipedia.org/wiki/Unix_time). To find out what the epoch is on a given platform, look at `gmtime(0)`.
Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.
Just use time.time hehe
?
Thanks!
(:
@maiden fable
I forgot this don't use discord's epoch and use the normal one 
message isn't defined
!d datetime.datetime.timestamp
datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3.10/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3.10/library/time.html#time.time "time.time").
Naive [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3.10/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.
For aware [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:
```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
``` New in version 3.3.
Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
there is also fromtimestamp
ok, thanks!
how to use this?
how do i get all msgs in a channel?
!d discord.TextChannel.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...
@maiden fable
I am tryna make it so it prints before and after nickname change but it gives me the error at the bottom
what if i dont want to add any name to discord.py embeds add_Field command
it only takes 2 arguments
ahh
the member object before the change and after
should I remove member?
yes
but now when I print member.mention it says member is not defined
round.add_field(name="hm",value=statements[_],inline=False) ```
how can i remove name
!d discord.CategoryChannel.channels
channels```
Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels.
how to use this
for checking this
but how to get that list
thats the issue
CategoryChannel doesn't define __contains__
``Ignoring exception in command play:
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 "/home/runner/bestbot/cogs/music.py", line 26, in play
ctx.voice_client.stop()
AttributeError: 'NoneType' object has no attribute 'stop'
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: AttributeError: 'NoneType' object has no attribute 'stop``
discord.CategoryChannel.channels returns a list
any help pls pls pls
!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.
check if ctx.voice_client is None
like i need to do
catedoryname.channels
???
then stop it if its not
!ytdl @honest hazel
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)
raise TypeError("command_prefix must be plain string, iterable of strings, or callable "
TypeError: command_prefix must be plain string, iterable of strings, or callable returning either of these, not NoneType
no, categoryobject.channels
you passed in a malformed prefix
ok
yes
i got it lemme try once
ctx.voice_client.None()
no
like this?
check if ctx.voice_client is None
when I print member.mention it says member is not defined @hasty iron
ctx.voice_client.stop() is None?
voice_client can return None if there isnt any
you have 2 member objects use one of them
leme try
!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...
ahhhh
both of those are member objects
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 "/home/runner/bestbot/cogs/music.py", line 33, in play
url2 = info['format'][0]['url']
TypeError: string indices must be integers
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: TypeError: string indices must be integers```
Pls pls pls help
@hasty iron help?
no
why not
hmm
its just print(info)
?
print(info) before url2 = info['format'][0]['url']
hmm
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
print(info)
url2 = info['format'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)```
is this right?
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)
i cant provide further help sorry
and i also want that like if the person search instead of url
i want like the person search the keywords instead of using url
how we can do this?
i cant help you sorry
why tho
was it solved?
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
dm pls?
i dont do dm help
Yeah its fixed now
aight
but I used member for a different part which was the issue
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: AttributeError: 'NoneType' object has no attribute 'stop'```
When it says something is already a command does that mean python recognises the word so I cant use it?
yeah
i think its same error
I am trying to make a .help command but it says the command is already a thing
remove help command
u need to remove
it
2 command names can't have the same name
what do you mean? I only have one async def help
What is the "new" module that will replace discord.py considering that the discord.py dev discontinued it?
bot = commands.Bot(*args, **kwargs, help_command=None)
So there is no way for me to use .help in my bot?
there is a default help command
you have to remove it first
how can I remove it?
you'll have to wait for a fork that is maintained or use another library
oh thank you
in the helps.cogs
Yep, but what is the best one?
this isn't suggested
i use cogs so yea
Nextcord?
oh ok sry leme remove
I have no idea which one I can use/learn
you can try edpy tbh. it's the closest to the actual dpy lib
any one help?
it says kwargs and args isnt defined
how/where do I define it
How can I make bot mention the person that I'm mention
@bot.command()
async def hack(ctx,*,message=""):
message = await ctx.send(f"Starting the hack for {#user.mention}...")
await asyncio.sleep(0.5)
await message.edit(content="**[25%]** Finding Ip...")
await asyncio.sleep(0.5)
await message.edit(content="**[50%]** Found successfully the IP")
await asyncio.sleep(0.5)
await message.edit(content="**[57%]** Looking for email and password...!")
await asyncio.sleep(0.3)
await message.edit(content=f"**[75%]** DONE! email : {#user.name}@gmail.com` | password : `salM32{#user.name}52r")
await asyncio.sleep(0.6)
await message.edit(content=f"**[100%]** Done hacking {#user.mention}")
await asyncio.sleep(0.3)
await message.edit(content=f" {ctx.author.mention}I will send you the info dm😄!")
await asyncio.sleep(1.5)
await ctx.author.send(f"Email: `{#user.mention}@gmail.com`\n Password: salM32{user.name}52r")
that looks illegal
help pls?
both are good tbh
still waiting
?
bot constructor?
what is this with ytdl yeah we can't help you
uh
sorry I am pretty new to discord.py and python
so is there any way we can fix?
where you defined commands.Bot()
@slate swan
Oh thnks, which one you think is the best one? Hikari, enhanced or Nextcord?
okay, do client = commands.Bot(command_prefix = '.', intents=intents, help_command=None
essentially, args mean arguements, and kwargs mean key word arguements.
ty
Can someone share an example of how to move an existing text channel to a category?
I found this in the docs but not sure how to implement: https://discordpy.readthedocs.io/en/stable/api.html?highlight=move#discord.TextChannel.move
oh okayyy
which was what i meant when i wrote that
honestly, right now i'd say hikari
so you wanted me replace your args and kwargs with what it actually should be
it has slash commands already implmented
args the the positional arguements, kwargs are optional
category = discord.utils.get(member.guild.categories, name='Verification-Logger')
log = discord.utils.get(channels, name="zenesis-verification-logger")
print(category)
print(log)
cat = category.channels
print(cat)
if category is None:
overrides = {member.guild.default_role: discord.PermissionOverwrite(send_messages=False, read_messages=False)}
position = 0
category = await member.guild.create_category(name="Verification-Logger", overwrites=overrides, reason = "Zenesis verification system" ,position = position)
if log not in cat:
log = await member.guild.create_text_channel("Zenesis-Verification-Logger", category=category)
guys my bot is making the channel even if it is in the category but why?
for example, on the on_message event, you need to do on_message(message), so message is an arguement. not kwarg, because you need to put it
K, thx. Just one more question does it have Cogs?
someone help
Or something similar?
hikari? yes
!pypi hikari
someone help
thx, I will try hikari
use category=
So what would that look like? discord.TextChannel.move(category=category)? I'm new to reading docs.
I just told u. category.channels dude
category.channels returns the list of channels in that category
yep i saw it returned
Then try to find the channel in the list of channels.
I don't understand your code well. Could you please use a code pasting website?
!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.
ok
this is what i am trying to do
@dapper cobalt
I'm reading it you don't have to ping me many times..
ok
me wanna make a channel only if the channel is not in the category
but its creating it everytime
API question: if I get a message of type GUILD_DISCOVERY_DISQUALIFIED, what is its author going to be?
author is specified as non-optional and non-nullable... so what is it?
anyone?
not working
Error?
channel.history is an async iterator, you need to use an async for loop instead of a normal one, ```py
async for message in channel.history():
print("your message: ", message.content)
this uses an API call every 100 message you iterate so
skipping it xd
Am i doing anything wrong?
@bot.event
async def on_member_remove(ctx, member):
await ctx.guild.ban(member)
print(f"Banned {member} ")
why it ain't banning when i leave
on_member_remove only receive member, you can't just add ctx and expect it to give you, remove it, if you want to ban the member, use member.ban instead
Ah
so i need to remove it right?
yes remove ctx from the parameter, as it only take 1 pos argument
Still not banning tho-
is the print not printing?
yes
do you have member intents
why are you reading 100 messages anyways
!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.
counting them
like, the whole channel or just 100 messages
is there any other way?
count them
whole channel
that's the only way, unless you want to count them from on_message and store them on a db
i am trying to do exactly that
the unless part
for example, fetching all messages of this channel (#discord-bots) is too many api calls
1 api call for every 100 messages
yes i get that
it wont get you banned to be fair, it would just be slow, from my experience 14 mil messages would take about 4 - 5 hours
insert into your db (author_id, message_counts, channel_id)
and increment message_counts on_message
would that count the previous msgs too?
no
how do i count prev msgs or it is same like you said before - too many api callss, i shouldnt count them
Ah-
My Ready is Body
Ignoring exception in on_member_remove
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "<string>", line 98, in on_member_remove
TypeError: ban() takes 1 positional argument but 2 were given
yeah
lemme read it
show error code
code*
shouldnt then?
@bot.event
async def on_member_remove(member):
await member.ban(member)
print(f"Banned {member} ")
that's your choice but i dont recommend doing it
it doesn't take any pos arguments, just member.ban()
Alrighty
well if it get me in trouble i wont, just confirming from you, i am bit confused xd
Working fine tysm!
there really aren't any other way than just channe.history() for previous messages
Im new to this language haha-
@client.event
async def on_message(message):
for i in message.content:
if i == "test":
em = discord.Embed(description="dont try me bro")
em.set_footer(text="Code by: A__Guy")
await message.author.send(embed=em)
await message.delete(seconds=1)
``` i dont get any errors from this and it still doesnt work
learn python before discord.py 
!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.
for i in message.content, you're iterating each character of message.content, so i will never be "test"
I immediately learn discord.js before js tho 
js != python
API question: if I get a message of type GUILD_DISCOVERY_DISQUALIFIED, what is its author going to be?
author is specified as non-optional and non-nullable... so what is it?
Traceback (most recent call last):
File "main.py", line 293, in <module>
client.run("token not provided so no people can steal bois")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start
await self.login(args, bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 216, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
how do i fix this
||again, mod questions are hard to understand||
how would i only watch for that word then
use in, ```py
content = "abctest"
"test" in content
True
"test!" in content
False
someone
You are making too many requests to the api.
basically, you were ban from discord, you have to wait until you get unbanned
you use replit?
my bot got banned?
yeah
reply
why
ye?
that is it
hm
@eager bolt Not really "banned". APIs usually have a limit on how often you can request them, and if you go over that limit, you're put on cooldown. That's called "rate limiting".
read ^^ the first part
discord.py is discontinued why?
huh
sorry for ping 
oh
aha okay
Read the top pin in this channel
ok
im still so confused
oh
in will check if the left side contains elements on the right side, so if you try to apply it in your case, you can just do ```py
if "test" in message.content:
# do your stuff
How do i do this?
!d discord.User.bot
Specifies if the user is a bot account.
How do i add it in my code?
help me gaiz
help
help me
Where do i add it in my code?
XD
Ok dude where?
guilds.user
?
help
wht should i define server with
ohk thnx
use either one
await member.send(f"ejtnkgresgm")
bro
its saying Context not defined
ctx.guild
what, slash commands?
yes
its not working
how?
how to use bot object in help command
just do you have been kicked in ctx.guild.name
in other cogs we can us it as self.client
ohk
if you use self.client in cogs you should be able to use client without cogs
Why does it shows smthing like this?
Nop
??
async def is_blacklisted(self, target_id: int):
if target_id in self.admin:
return False
if target_id in self.blacklisted:
return True
async with self.pool.acquire(timeout=constants.Time.db_time) as conn:
data = await conn.fetch(
"""SELECT target FROM blacklist WHERE target = ($1)""", target_id
)
if data:
self.blacklisted.append(target_id)
return True
return False```
Anyone has any way to make this not open the db all the time?
For just a normal command
bruh, use f strings
!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.
You can cache the data in the database
Ah
Wdym?
But theres no example..
do you need one?
It's a boolean
Yup
and what for
Do you even need an example
thnx
You can load the data in the db into the ram
@client.command()
async def arena(ctx, p1: discord.Member, p2: discord.Member):
player1 = p1
player2 = p2
p1health = 100
p2health = 100
turn = random.choice([player1.id,player2.id])
import asyncio
await ctx.send(embed = discord.Embed(title=":stadium: **Arena Fight Begins**",description=f"{p1.mention} is up against {p2.mention}! **Match will begin very shortly..!** \n**{p1.name}** **vs****{p2.name}**",color=discord.Color.teal()).set_thumbnail(url="https://media.discordapp.net/attachments/693517202879414312/860599179578966056/Fight_icon.png"))
await asyncio.sleep(3.0) #shortly
stunOn = False #this tracks the stun count
while True:
turn_member = await ctx.guild.fetch_member(turn)
victim_member = await ctx.guild.fetch_member(player1.id if turn == player2.id else player2.id)
fp1_Damage = random.randint(0, 10)
ok1_Damage = random.randint(0, 20)
ps1_Damage = random.randint(0, 20)
rb1_Damage = random.randint(5, 10)
ss1_Damage = random.randint(0, 50)
embed = discord.Embed(title='🎫 Player Turn',description=f"It's {turn_member.mention}'s turn! Choose an action:\n**Weapons Commands:** `fp1`, `ok1`, `ps1`, `rb1`, `ss1` \n`playerhealth`, `or endgame`",color=discord.Colour.teal())
await ctx.send(embed=embed)
msg = await client.wait_for('message', check=lambda m: m.channel == ctx.channel and m.author.id == turn)
msgc = msg.content.lower()
Iirc that won't work. I made a persistent database pool once and tried to use it and it raised some errors. You need to open a pool everytime you use database 
what? open a pool everytime?
Yes-
@bot.command()
async def something(ctx, member:discord.Member):
if member == bot.user:
#code
else:
#code
what are "some errors"
Ok ty
it could've been on your end
just use self.pool.fetch instead, this will internally uses acquire
Anyone got any project ideas thats the same difficulty as a discord bot?
hm
I think that you can use pandas to do that
What do you mean by internally?
thats because acquire creates a new connection
and you stored that connection
and used it everywehre
asyncpg/pool.py lines 545 to 555
async def fetch(self, query, *args, timeout=None) -> list:
"""Run a query and return the results as a list of :class:`Record`.
Pool performs this operation using one of its connections. Other than
that, it behaves identically to
:meth:`Connection.fetch() <asyncpg.connection.Connection.fetch>`.
.. versionadded:: 0.10.0
"""
async with self.acquire() as con:
return await con.fetch(query, *args, timeout=timeout)```
Wait did I say pool?
Sorry I meant connection
What if I want to make two oprations?
Undefined term "bot"
just make two operations...?
firstly it isn't discord.Member, use p1
and use client.user
you haven't defined bot
Then use acquire it will do both in the same transaction
I used memeber but it said undefined name "member
bruh, i was giving you an example
Ok wht abt p2?
don't copy paste, just try to understand..
same thing
Hmm
If you can't differentiate between a class and it's instance then probably you should go back and learn some python
instead of client.command()?
Wait so I should use:
class Bot(commands.Bot):
__init__:
self.pool = self.loop.run_until_complete(asyncpg.create_pool(dsn=dsn))
async def fetch(self, query, *args, timeout=None):
async with self.pool.acquire() as conn:
return await conn.fetch(query, *args, timeout=timeout)```
Like coming here to get spoonfed every single line of your code isn't a way to learn

There is pool.fetch
You can use that if you are doing a single operation
If you are doing multiple, you should probably do it under the same transaction
it's basically what you defined commands.Bot as + .user. if you are given code just please don't copy paste it without understanding it 
Oh yeah ok, thanks
async def is_blacklisted(self, target_id: int):
if target_id in self.admin:
return False
if target_id in self.blacklisted:
return True
data = await self.pool.fetch(
"""SELECT target FROM blacklist WHERE target = ($1)""", target_id
)
if data:
self.blacklisted.append(target_id)
return True
return False```
(Inside commands.Bot subclas)
?
How do I send a PM? I tried client.send_message() but it turns out that's deprecated, not sure what to use
thnx bruh
may i add u as frnd
!d discord.User.send
await send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed "discord.Embed") and it must be a rich embed type.
i've tried client.get_user(user).send(msg_), it gives me AttributeError: 'NoneType' object has no attribute 'send'
it means get_user is returning None, that user id is not cached
rewrote it to this
async def send_message(msg_, user_id):
user = await client.fetch_user(user_id)
await user.send(msg_)
def msg(msg_, user_id):
loop = asyncio.get_event_loop()
coroutine = send_message(msg_, user_id)
loop.run_until_complete(coroutine)
giving me this now
RuntimeWarning: coroutine 'send_message' was never awaited
pass
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
huh, are you running the bot at all, what's preventing you from not just awaiting it
trying to run msg() synchronously
i'll try to rewrite it to run the stuff I want from the on_ready() event
just use loop.create_task instead of run_until_complete
Hey can someone tell me what's wrong with my code?
@commands.Cog.listener()
async def on_ready(self, ctx):
self = ctx.guild
channel = self.client.get_channel('883012878783901766')
role = discord.utils.get(self.roles, name="Verified")
message = await self.client.send_message(channel, "React to me to verify yourself!")
while True:
reaction = await self.client.wait_for_reaction(emoji="✅", message=message)
await self.client.add_roles(reaction.message.author, role)
id's are integers not strings
This is my error
Traceback (most recent call last):
File "C:\Users\Sam Jorden\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
TypeError: on_ready() missing 1 required positional argument: 'ctx'
and on_ready does not take any arguments
So what do I do?
this solved my problem, runs fine now
Where do I put self and ctx then?
Context only gets passed into commands
So I have to rewrite this?
i have this bot that adds up scores on each message like 1 point per message. how do i put a point cap on how many points max per minute?
if i want to change color then
hello I need help in a code, it turns out that I want to do the command "rolmuted", everything works, but how do I do when they have not defined a role in a guild? If I do, it sends an error, I don't know how to fix it
i have an invalid syntax error on a command declaration. i'm using python 3.7 and pycharm expects a 'for' there (for some reason). any idea on what's causing the syntax error?
?
How to use slash in cogs
what module ae you using
discord_slash
from discord_slash import SlashCommand
what are Cogs for?
woah what does that module do?
Trying to move a text channel to the "archived" category:
category = discord.utils.get(ctx.guild.categories, name="archived")
channel = get(ctx.guild.channels, name=event)
await discord.TextChannel.move(channel, category=category)```
Here's the error I get:
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: Could not resolve appropriate move position```
How can i check if the author is in the same voice channel with the bot?
Why is my bot sending the help section twice when I do .help
when I do .help it gives me the help commands twice
have you tried restarting your bot
yeah
sends links will ju?
its on my profile
I got rid of cogs
cause it caused problems
is the bot being hosted twice somewhere?
perhaps you left a console open or something
ive closed vs code but the bot is still online?
it doesn’t turn offline immediately
try using a command, it takes around 2 minutes until the bot changes the presence
It usually takes a minute or two to reflect.
awhhh its fixed now thanks
Thanks @limber cosmos
have you got a solid python foundation to work on?
Yes
muy bien
Pls English
very good :)
How would I do that when no role has been registered in the server, send a message when they want to execute the mute command? please
async def setmuterole(self, ctx, role_id:int):
with open("rolmute.json", "r") as f:
rolmute = json.load(f)
rolmute[str(ctx.guild.id)] = role_id
with open("rolmute.json", "w") as f:
json.dump(rolmute, f, indent=4)
embed = discord.Embed(description=f'Se ha cambiado rol mute al rol <@&{role_id}>', color = ctx.guild.me.top_role.color)
await ctx.send(embed=embed)```
oml please someone help me
with open("rolmute.json", "r") as f:
rolmute = json.load(f)
if str(ctx.guild.id) not in rolmute:
await ctx.send("No mute role has been registered.")
return
implement that in the mute command, I recommend using a database such as sqlite instead of json and you should check if the mute id is valid
With?
I'm coding a discord bot
with no coding experience whatsoever
and I've run into a problem
Why not just try and look for a role named muted from ctx.guild
yep you can do that too
I still don't learn how to use the db, I am using this as an alternative, but they already told me before that they are better, avoid errors and are faster, I will use them soon, thanks
i will try to do that
okay good luck
It is a bot in Spanish, I have seen servers where they have the name of the muted role very funny and I would like it better that way
shows
exactly, thats why i do not like looking for the role by name
k
yeah
import discord
from discord.ext import commands
client = commands.bot(command_prefix = '.')
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
Traceback (most recent call last):
File "main.py", line 4, in <module>
client = commands.bot(command_prefix = '.')
TypeError: 'module' object is not callable
alrighty
so there are two types of bots in discord.py
a client which does not include any command features etc, kinda like discord.js
and a bot which includes all of these features
now, you should always use a bot, I dont see why you would use a client
basically you created a bot and then overridden that bot with a client
so just remove that line that has this code:
client = discord.Client()
AND you have a typo in commands.Bot, it should be commands.Bot, not commands.bot
capital letters matter a lot
oh lord I'm seeing that now
client doesn't support command features?
is it fine if I post all the code here? it's only 50 lines
if you want to send a code like this
client = discord.Client()
use` three on each side
``
well no if you use a client you cant do client.command
Yes do not worry
!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.
right, right
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('compliment me'):
await message.channel.send('u suck')
if message.content.startswith('LOL'):
await message.channel.send('licking oversized lameasses')
if message.content.startswith('Compliment me'):
await message.channel.send('u suck')
if message.content.startswith('insult me'):
await message.channel.send('u suck')
if message.content.startswith('lol'):
await message.channel.send('licking oversized lameasses')
if message.content.startswith('Im so cool'):
await message.channel.send('no your not, fuck you')
if message.content.startswith('Hello'):
await message.channel.send('no one likes you loser')
@client.command()
async def kick(ctx, member : discord.member, *, reason=none):
await member.kick(reason=reason)
@client.command()
async def ban(ctx, member : discord.member, *, reason=none):
await member.ban(reason=reason)
client.run('my bot token is here so just replacing it')
it worked, replacing bot with Bot, but now a new prob
Traceback (most recent call last):
File "main.py", line 43, in <module>
@client.command()
AttributeError: 'Client' object has no attribute 'command'
yes but you should still delete the following line:
client = discord.Client()
ok
and one more thing, in you ban and kick commands replace none by None and replace discord.member by discord.Member
your kick and ban commands probably dont work too, you have an on_message event that breaks the command invoker
so you should add this:
await bot.process_commands(message)
to your on_message event and you shouldnt really use on_message to make commands, you should use normal commands kinda like the ban and kick commands you made
if you want to use on_message use @client.listen('on_message') instead
i hope thats right
uhh doesnt really matter but ok
oh it does? hmm, perhaps client.listen adds and event and client.event overrides the normal one
correct
yeah they dont work
well where should I put await bot.process_commands(message)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
how do i catch this exeception?
attempting to use discord.Forbidden results in failure
Hey!! How do i make an event code only work if an specific user or role uses it.
if ctx.message.author.id == "yourid": do something
Thanks.
or
async def on_command_error(ctx, error):
if isinstance(error, discord.Forbidden):
# handle here
``` this should work
i tried it
unable to catch
Is the bot missing perms or the user?
if isinstance(error, discord.Forbidden):
embed = discord.Embed(title="Access Denied").add_field(name="Error", value="Member mentioned has higher role order than me and/or is a Moderator.")
await ctx.channel.send(embed=embed)
Hmm. Try printing out type(error) and see if it's of a different type or something
this should work in theory but in practise doesnt
if isinstance(error, commands.MissingPermissons)```
ah yes
then it should send this one
Just want to mention, that Missing Permissions could also happen if the bot is not given the proper permissions to do something.
So your response here might be misleading
if isinstance(error, commands.MissingPermissions):
embed = discord.Embed(title="Access Denied").add_field(
name="Missing Permissions", value="BAN_MEMBERS"
)
await ctx.channel.send(embed=embed)
If the bot doesn't have permissions just add Bot in front of MissingPermissons in a elif statement.
this handles if the author has perms
I will now try that, Thank you, my good sire!
Ah. Yeah, you can tell I don't do much with error handling in discord.py
async def on_message(message):
if "LFT" not in message.channel.topic:
return
if message.author.bot:
return
else:
if "Yes" in message.content.lower(
) or "yes" in message.content.lower():
await message.channel.send(
f"<@&878729538518016080>\n\n🔎 {message.author.mention} **Is looking for team.**"
)```
idk were to add it there
i tried many ways
this
Followup: Does not work
Doesn't send the message?
more info: this exception occurs when an admin tries to ban an admin with the same role order
@plain egret were should i add it?
You have to check if the author has the same role as the user mentioned.
no no
if ctx.author.top_role == member.top_role:
return await ctx.send("You have the same highest role.")```
Yeah.
@plain egret Im having some problems
I dont know were to place it it always give an error and i want it to be a role not an user id
@vale pendant Could you help me
You want a command to be role only?
thanks :)
Of course.
a event
A event?
Hmmmm, you can possibly try grabbing the role then checking if the user has that role.
role = discord.utils.get(message.guild.roles, name="role")
if role in message.author.roles:
# do something```
Ok ill test it
File "main.py", line 141, in <module>
role = discord.utils.get(message.guild.roles, name="Owner")
NameError: name 'message' is not defined```
k
async def on_message(message):
if "LFT" not in message.channel.topic:
return
if message.author.bot:
return
else:
if "Yes" in message.content.lower(
) or "yes" in message.content.lower():
await message.channel.send(
f"<@&878729538518016080>\n\n🔎 {message.author.mention} **Is looking for team.**"
)```
thats the code
its alr defined hm
You have to put this in your code.
That doesn't matter yet.
oh
So you want this event to be a certain role only?
yea
@bot.listen("on_message")
async def on_message(message):
role = discord.utils.get(message.guild.role, name="role-name")
if role not in message.author.roles:
return
if "LFT" not in message.channel.topic:
return
if message.author.bot:
return
else:
if "Yes" in message.content.lower(
) or "yes" in message.content.lower():
await message.channel.send(
f"<@&878729538518016080>\n\n🔎 {message.author.mention} **Is looking for team.**"
)```
Thanks ill test it
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "main.py", line 145, in on_message
role = discord.utils.get(message.guild.role, name="Owner")
AttributeError: 'Guild' object has no attribute 'role'
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "main.py", line 194, in test
if str(reaction.emoji) == '🔎':
UnboundLocalError: local variable 'reaction' referenced before assignment
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "main.py", line 244, in on_message
embed_mess = await message.channel.send(embed=embed)
UnboundLocalError: local variable 'embed' referenced before assignment```
fix message.guild.role to message.guild.roles my bad.
alr np
@commands.Cog.listener()
async def on_ready(self):
self.meme.start()
self.nsfw.start()
channel = self.bot.get_channel(864021067264557087)
cogs = ', '.join(self.bot.cogs)
o = discord.Embed(title=f"🤖 {self.bot.user} is now online.", description=f":python: Python `{str(sys.version).split(' ')[0]}`\n:dpy: Discord `{discord.__version__}`\n:jishaku: Jishaku `{jishaku.__version__}`\n{':Working: Task `Meme is running`' if self.meme.is_running() is True else ':not: `Meme is not running`'}\n:Working: Cogs loaded `{cogs}`", timestamp = datetime.utcnow(), colour=0x3d025f)
await channel.send(embed=o)
await self.bot.get_channel(862915601332699137).connect(reconnect=True)
await self.bot.get_channel(844178791735885824).connect(reconnect=True)
``` will this code make the bot go offline after a few hours of running
Wdym?
Yes!! it works tysm.
Yeah, of course.
@commands.command()
@commands.has_permissions(manage_messages=True)
async def clear(self,ctx):
deleted = await ctx.channel.purge(limit=100,)
await ctx.channel.send('Deleted {} message(s)'.format(len(deleted)))
``` do i need a check function ? 
when using on_command is there a way to check what command was ran?
maybe a print statement at the end ?
check for?
?
ctx.command returns the commands.Command object
how i make so the bot deletes one message on an event
class clear(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.has_permissions(manage_messages=True)
async def clear(self,ctx):
deleted = await ctx.channel.purge(limit=100,check=check)
await ctx.channel.send('Deleted {} message(s)'.format(len(deleted)))
``` my clear command is broken 
Whats wrong with it?
check is not defined
how do i define message for messages in a channel?
how i make so the bot deletes one message on an event
you mean channel.history?
@waxen granite
only message that user sent
message.delete()
what's the problem with it
async def test(message):
role = discord.utils.get(message.guild.roles, name=".")
if role not in message.author.roles:
return
if "LFT" not in message.channel.topic:
return
if message.author.bot:
return
await message.delete()```
i guess you didn't define message
and dont work
just bot.listen
i did:/
you return
and the function's name is gonna be the event
you used return
@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"``^urban [Word]``")``` help, error message wont send
confused
and yeah
do you understand what return do?
yes
then
make the command dont work

why you use it
ugh
lol
it leaves the function
yea
remove the return before messsage.delete()
it return a value and the function stops
@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"``^urban [Word]``")``` help, error message wont send
!e ```py
def x():
return "hello"
print(x())
@high flame :white_check_mark: Your eval job has completed with return code 0.
hello
no output?
wdym
oh
also, this is kinda off the point, but you can do
async def urban(ctx, *, msg)
theres no error message so
oh ok i think i forgot the comma
what did you type in discord?
it is on point, doing *args makes it optional
@slate swan it worked, thanks
!e ```py
def foo(*args):
print(args):
foo()
oops
!e
def foo(*args):
print(args)
foo()
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
()
this was so accidental lmao
anyone got a list of colors u can use for an embed?
!d discord.Colour
class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)").
There is an alias for this called Color.
`x == y` Checks if two colours are equal.
`x != y` Checks if two colours are not equal.
`hash(x)` Return the colour’s hash.
`str(x)` Returns the hex format for the colour.
and u don't need that word line
fuk why cogs not work
lol
!d discord.ext.commands.Cog
class discord.ext.commands.Cog```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
Delete function didnt work @slate swan could i send you the full code in dms
ok
@bot.listen("on_message")
async def on_message(message):
role = discord.utils.get(message.guild.roles, name=".")
if role not in message.author.roles:
return
if "LFT" not in message.channel.topic:
return
if message.author.bot:
return
else:
if "Yes" in message.content.lower(
) or "yes" in message.content.lower():
await message.channel.send(
f"<@&881199455473381447>\n\n:mag_right: {message.author.mention} **Is looking for team.**"
)
yesrole = get(message.guild.roles, id=883048286007742465)
await message.author.remove_roles(yesrole)
await message.delete()```

so what exactly is the error?
does it delete the member's role
weird
!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.
do you have the permission to do that?
to do what
delete messages
He doesn’t need permissions.
you need the manage_messages for that
If you read it says “Your own messages could he deleted without any proper permissions”
he doesn't want to delete his own message
only one message
He wants to delete the author message correct?
purge one message
I understand
kk
Hmmm.
do you have an error handler?
it doesnt give an error
answer the question
it would delete the message that was sent
@bot.command()
@commands.has_permissions(administrator=True)
async def ban(self, ctx, member:discord.Member, *, reason=None):
guild = ctx.guild
author = ctx.message.author
if author.guild_permissions.administrator == False:
embed4=discord.Embed(color=discord.Colour.red(), timestamp=datetime.datetime.utcnow(), title="Missing Permissions!", description="You don't have the required permissions to use this command!")
message1 = await ctx.send(embed=embed4)
sleeper=5
await asyncio.sleep(sleeper)
await message1.delete()
return
if member.guild_permissions.administrator and member != None:
embed=discord.Embed(color=discord.Colour.red(), title="Administrator", description="This user is an administrator and is not allowed to be banned.")
message2 = await ctx.send(embed=embed)
sleeper=5
await asyncio.sleep(sleeper)
await message2.delete()
return
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```
huh
since you specified the message in the event's parameters
What did I do wrong here?
if it sends you a message and deletes the member's "yesrole", it should delete the message that invoked the event too
otherwise it would throw an error, since you don't have an error handler that would ignore it
@bot.command()
@commands.has_permissions(administrator=True)
async def ban(self, ctx, member:discord.Member, *, reason=None):
guild = ctx.guild
author = ctx.message.author
if author.guild_permissions.administrator == False:
embed4=discord.Embed(color=discord.Colour.red(), timestamp=datetime.datetime.utcnow(), title="Missing Permissions!", description="You don't have the required permissions to use this command!")
message1 = await ctx.send(embed=embed4)
sleeper=5
await asyncio.sleep(sleeper)
await message1.delete()
return
if member.guild_permissions.administrator and member != None:
embed=discord.Embed(color=discord.Colour.red(), title="Administrator", description="This user is an administrator and is not allowed to be banned.")
message2 = await ctx.send(embed=embed)
sleeper=5
await asyncio.sleep(sleeper)
await message2.delete()
return
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```
do you want to delete the bot's message or the user's message?
user
or just delete 1 message
both could work
ctx.message.delete()
on_message event
await ctx.message.delete()```
on_message event
wawit
?
he did the right thing
he wants to delete the message sent by user after executing the command right ?
what
cause code only worked if it had the role
and i added the function when it was already removed
i was looking at another code and thought it was yours lmao
i readed the code twice and noticed
id say change perms to ban and whats the issue ?
it doesn't actually ban the person
or work
he didn't provide a single error
nice ig
send an error
or the output
where
show us where it stopped working
if it has thrown an error
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.```
you used the command incorrectly
that's all
you didnt mention the user ur trying to ban maybe ? i'd say make a error handler and send it
so you can notify the user
but I just come to realise
i did
you used @bot.command()
i dont use client
so you're not in a cog
Why did you put self?
ur using @bot command in a cog ?
then why do you have a self arg
i think hes in a cog file 
why
since hes using @commands.has_permission
and self
If he was in a cog he would use @commands.command
I think he may of copied it off a site like stack overflow
maybe
- why do you have message 1 message 2 and etc.
that would be the thing causing the error right ,
how about we ask then 
yes.
message3 = ctx.send(embed=embed1)
sleeper=5
await asyncio.sleep(sleeper)
await message3.delete()
return``` This is just a pain to look at.
im not in a cog file
judging from your code its a bit bad
if you copied it from someone then that explains why its not working
remove self
you can do await ctx.send(embed=embed, delete_after=3)
replace @commands.has_perms to @has_permissions(wtv perm=True)
you didn't put await in front of ctx.send.
you said ur not
There's alot of errors.
