#discord-bots

1 messages · Page 441 of 1

gloomy coral
#

its a custom moji

#

AH got it

#
 await ctx.send("<@&877978160489201724>")```
lament mesa
#

is :trash: a custom emoji?

gloomy coral
#

the & sign

gloomy coral
#

it wld work be4

zinc lion
gloomy coral
#

bruh

#

dont copy paste

river kindle
#

please help

zinc lion
lament mesa
gloomy coral
#

see now

gloomy coral
river kindle
#

need some help^^^

zinc lion
#

well i wouldnt copy, it just didnt make sense. let me try it

gloomy coral
#

Wait

#

@lament mesa

#

it is tht way

lament mesa
#

yes

#

what way?

gloomy coral
#
await message.add_reaction('![trash](https://cdn.discordapp.com/emojis/867001275634417714.webp?size=128 "trash")')

        def check(reaction, user):
            return reaction.message == message and str(
                reaction.emoji) == '![trash](https://cdn.discordapp.com/emojis/867001275634417714.webp?size=128 "trash")' and user == ctx.author

        await self.bot.wait_for('reaction_add', check=check)

        await message.delete()```
lament mesa
#

oh wait

#

discord.Message doesnt have __eq__

#

That means you cant compare 2 Message objects

agile goblet
#

compare ids

lament mesa
gloomy coral
#

k

stark bobcat
#

Can you send a embed to user dms

signal forge
#

why not?

stark bobcat
#

Oh

signal forge
#

this is a DM

stark bobcat
#

Oh okay thanks

proven elm
#
@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

spring flax
#

so you should be doing on_member_update

proven elm
spring flax
#

and since before and after are member objects, they too would have the dispaly_name or mention attr

proven elm
#
@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

stiff knot
#

Anyone know why line 44 indentation isn't right?

slate swan
proven elm
#

damnnnn thankk you

muted gale
lament mesa
#

nothing

#

forks will be made

slate swan
muted gale
#

will it still work when the api updates?

slate swan
#

Like there's already edpy, hikari, etc.

slate swan
muted gale
#

oh ok

proven elm
signal forge
proven elm
waxen granite
#

is there a way for a bot to be able to change the name of guild owner?

signal forge
proven elm
#

these are my extensions

#

pretty sure its rainbow brackets and monokai pro

#

and also material icons theme

signal forge
#

lovely tyty

spring flax
stiff knot
#

fields = [("Owner", ctx.guild.owner, True),

#

Does anyone know why ctx.guild.owner is returning none?

amber imp
#

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

slate swan
#

!code

unkempt canyonBOT
#

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.

slate swan
#
@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

spring flax
slate swan
#

Oh

#

But then I’m confuse why it’s writing at process commands

spring flax
slate swan
#

Hold on

slate swan
#

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

zinc lion
#

what doespy pass_context=Truedo

spring flax
#

it is outdated

slate swan
zinc lion
peak rune
#

how to get bot username and tag python

slate swan
#

I think I know my error

spring flax
#
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
spring flax
spring flax
zinc lion
hoary gust
#

guys how can i check that if a channel is in a particular category or not

#

?

slate swan
hoary gust
#

@spring flax plz help

spring flax
amber imp
#

can anyone help me in creating a google search cmd ?

spring flax
#

it does not mean you can't use it now, but in 2022 you would need to switch

spring flax
unkempt canyonBOT
hoary gust
slate swan
peak rune
#

like: py print("logged into:" )

#

and then the username

spring flax
peak rune
slate swan
#

Dude he just showed @hoary gust

hoary gust
slate swan
peak rune
honest hazel
#

local variable 'voice_channel' referenced before assignment

peak rune
honest hazel
#

can any one tell me? why tho

hoary gust
peak rune
spring flax
#
print(f"{bot.user.name}#{bot.user.discriminator}")```
@peak rune
peak rune
#

thank you.

slate swan
#

@spring flax how long have u been coding

slate swan
#

Which line did the error appear

slate swan
hoary gust
#

hey guys how can i check the category, an simple example will be more helpful

honest hazel
maiden fable
#

!d discord.TextChannel.category

unkempt canyonBOT
hoary gust
slate swan
#

Bruh

maiden fable
#

.....?

hoary gust
#

thats the problem

maiden fable
#

Wym check bro?

spring flax
#

this would return the category of which the channel you specified falls under

spring flax
maiden fable
#

BTW did u know, not only discord.py but Python itself tries to convert the parameters to the same class it's typehinted to

honest hazel
waxen granite
#

how do i get/count a role mentioned in a specific channel's msgs?

honest hazel
#

python

slate swan
#

!code

unkempt canyonBOT
#

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.

honest hazel
#

``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``

maiden fable
#

Loop through all the messages and add a check to see if role.mention in message.content

honest hazel
#

here anysolution

slate swan
#
CREATE TABLE IF NOT EXISTS main(
      guild_id TEXT,
      loggingchannel INT,
      loggingstatus TEXT,
      pingableroles INT,
      prefixes TEXT
    )
    ''')

will this work

maiden fable
#

But it will count as api abuse anyways

slate swan
#

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>)

honest hazel
hoary gust
#

?

maiden fable
unkempt canyonBOT
#

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.
maiden fable
#

category.channels bro

slate swan
# maiden fable Indeed

How do you do it?
I can't find it on google or the docs, all it shows is standard timestamps

honest hazel
maiden fable
spring flax
honest hazel
# spring flax 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)) ``

spring flax
#

uh

#

!ytdl

unkempt canyonBOT
#

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)
slate swan
#

BRO I HATE MYSELF

#

LMAO

unkempt canyonBOT
#

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.
maiden fable
#

Just use time.time hehe

slate swan
#

wait it don't use discord one notlikeblob

#

oh my bad

maiden fable
#

?

slate swan
maiden fable
waxen granite
#

@maiden fable

slate swan
#

I forgot this don't use discord's epoch and use the normal one notlikeblob

maiden fable
#

message isn't defined

hasty iron
unkempt canyonBOT
#

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.
hasty iron
#

there is also fromtimestamp

slate swan
#

ok, thanks!

hoary gust
waxen granite
#

how do i get all msgs in a channel?

slate swan
unkempt canyonBOT
#

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...
hoary gust
#

@maiden fable

proven elm
#

I am tryna make it so it prints before and after nickname change but it gives me the error at the bottom

slate swan
#

what if i dont want to add any name to discord.py embeds add_Field command

proven elm
#

ahh

hasty iron
#

the member object before the change and after

proven elm
#

should I remove member?

hasty iron
#

yes

proven elm
#

but now when I print member.mention it says member is not defined

slate swan
#
round.add_field(name="hm",value=statements[_],inline=False)  ```
#

how can i remove name

hoary gust
#

!d discord.CategoryChannel.channels

unkempt canyonBOT
#

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.
hoary gust
#

how to use this

hasty iron
#

that returns a list

#

you need to check if the channel is inside that list

hoary gust
#

thats the issue

hasty iron
#

CategoryChannel doesn't define __contains__

honest hazel
#

``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``

hasty iron
#

discord.CategoryChannel.channels returns a list

slate swan
#

!code

unkempt canyonBOT
#

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.

hasty iron
hoary gust
#

???

hasty iron
#

then stop it if its not

spring flax
#

!ytdl @honest hazel

unkempt canyonBOT
#

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)
slate swan
#
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
hasty iron
hasty iron
honest hazel
#

u mean this?

slate swan
hasty iron
hoary gust
honest hazel
#

ctx.voice_client.None()

hasty iron
#

no

honest hazel
#

like this?

hasty iron
#

check if ctx.voice_client is None

proven elm
#

when I print member.mention it says member is not defined @hasty iron

honest hazel
#

ctx.voice_client.stop() is None?

hasty iron
#

voice_client can return None if there isnt any

hasty iron
honest hazel
#

leme try

hasty iron
#

!d discord.on_member_update

unkempt canyonBOT
#

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...
proven elm
#

ahhhh

hasty iron
#

both of those are member objects

honest hazel
#
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?

hasty iron
#

info is a string or info['format'][0] is a string

#

can you print info?

honest hazel
hasty iron
#

why not

honest hazel
#

hmm

hasty iron
#

its just print(info)

honest hazel
#

ok

#

so how i can fix this error? sir

hasty iron
#

print info first

#

show me the output

honest hazel
#

u want

#

that print(info) should be up then info['format'][0] this string?

honest hazel
hasty iron
#

print(info) before url2 = info['format'][0]['url']

honest hazel
#

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)```
honest hazel
hasty iron
#

yes

#

also

#

!ytdl

unkempt canyonBOT
#

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)
hasty iron
#

i cant provide further help sorry

honest hazel
#

and i also want that like if the person search instead of url

honest hazel
#

how we can do this?

hasty iron
#

i cant help you sorry

honest hazel
#

why tho

slate swan
hasty iron
#

ytdl violates youtube tos

#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

we told you not to put member as a arg already..

#

it's just before and after

honest hazel
hasty iron
#

i dont do dm help

proven elm
slate swan
#

aight

proven elm
#

but I used member for a different part which was the issue

honest hazel
# hasty iron i dont do dm help
  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'```
proven elm
#

When it says something is already a command does that mean python recognises the word so I cant use it?

slate swan
#

yeah

honest hazel
#

i think its same error

proven elm
#

I am trying to make a .help command but it says the command is already a thing

slate swan
#

2 command names can't have the same name

proven elm
#

what do you mean? I only have one async def help

light radish
#

What is the "new" module that will replace discord.py considering that the discord.py dev discontinued it?

slate swan
#

bot = commands.Bot(*args, **kwargs, help_command=None)

proven elm
#

So there is no way for me to use .help in my bot?

hasty iron
#

you have to remove it first

proven elm
#

how can I remove it?

slate swan
proven elm
#

oh thank you

honest hazel
#

in the helps.cogs

light radish
slate swan
#

this isn't suggested

honest hazel
#

i use cogs so yea

light radish
#

Nextcord?

honest hazel
light radish
#

I have no idea which one I can use/learn

slate swan
proven elm
#

how/where do I define it

slate swan
#

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")
slate swan
#

send your bot constructor

slate swan
#

or even try !pypi hikari

slate swan
#

both are good tbh

honest hazel
#

still waiting

slate swan
proven elm
slate swan
honest hazel
#

uh

proven elm
honest hazel
#

so is there any way we can fix?

slate swan
honest hazel
#

or remove ydl

#

ytdl

proven elm
#

@slate swan

light radish
slate swan
#

okay, do client = commands.Bot(command_prefix = '.', intents=intents, help_command=None

#

essentially, args mean arguements, and kwargs mean key word arguements.

proven elm
#

ty

limber cosmos
proven elm
#

oh okayyy

slate swan
#

which was what i meant when i wrote that

slate swan
proven elm
#

so you wanted me replace your args and kwargs with what it actually should be

slate swan
#

it has slash commands already implmented

slate swan
hoary gust
#
                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?

slate swan
#

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

light radish
hoary gust
#

someone help

light radish
#

Or something similar?

slate swan
#

!pypi hikari

unkempt canyonBOT
hoary gust
#

someone help

light radish
#

thx, I will try hikari

limber cosmos
maiden fable
hoary gust
#

can u explain

#

?

maiden fable
#

category.channels returns the list of channels in that category

hoary gust
dapper cobalt
#

Then try to find the channel in the list of channels.

hoary gust
#

but still why is it making the channel

#

@dapper cobalt ^

dapper cobalt
#

I don't understand your code well. Could you please use a code pasting website?

#

!paste

unkempt canyonBOT
#

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.

dapper cobalt
hoary gust
#

ok

#

me wanna make a channel only if the channel is not in the category

#

but its creating it everytime

dapper cobalt
#

@hoary gust try this

hoary gust
#

ok

#

lemme

tight obsidian
#

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?

waxen granite
#

anyone?

hoary gust
dapper cobalt
hoary gust
#

its just creating channels even if it exists

slate swan
#

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

waxen granite
#

skipping it xd

vale narwhal
#

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

slate swan
#

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

vale narwhal
#

so i need to remove it right?

slate swan
#

yes remove ctx from the parameter, as it only take 1 pos argument

vale narwhal
slate swan
#

is the print not printing?

vale narwhal
#

yes

slate swan
#

do you have member intents

vale narwhal
#

And not banning tho

#

lemme checj

#

oops seem like no

#

lemme try add it

slate swan
#

why are you reading 100 messages anyways

high flame
#

!intents

unkempt canyonBOT
#

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.

waxen granite
high flame
#

many api calls

#

i wouldn't do that

slate swan
#

like, the whole channel or just 100 messages

waxen granite
#

is there any other way?

high flame
waxen granite
slate swan
#

that's the only way, unless you want to count them from on_message and store them on a db

waxen granite
#

the unless part

high flame
#

1 api call for every 100 messages

waxen granite
#

yes i get that

slate swan
#

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

high flame
#

and increment message_counts on_message

waxen granite
#

would that count the previous msgs too?

high flame
#

no

waxen granite
#

how do i count prev msgs or it is same like you said before - too many api callss, i shouldnt count them

vale narwhal
#

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
high flame
#

yeah

vale narwhal
#

lemme read it

waxen granite
vale narwhal
#
@bot.event
async def on_member_remove(member):
	await member.ban(member)
	print(f"Banned {member} ")
high flame
slate swan
waxen granite
vale narwhal
#

Working fine tysm!

slate swan
#

there really aren't any other way than just channe.history() for previous messages

vale narwhal
#

Im new to this language haha-

regal rapids
#

@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
high flame
#

!d discord.Message.delete

unkempt canyonBOT
#

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.
high flame
#

delay

#

not seconds

#

if that's what you meant to do

slate swan
vale narwhal
tight obsidian
#

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?

eager bolt
#

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.

Discord Developer Portal

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

high flame
#

||again, mod questions are hard to understand||

regal rapids
slate swan
lament mesa
slate swan
high flame
#

yeah

high flame
eager bolt
#

why

eager bolt
high flame
eager bolt
#

hm

tight obsidian
#

@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".

high flame
#

read ^^ the first part

slate swan
spring flax
#

huh

high flame
#

sorry for ping rooBulli

spring flax
#

oh

tight obsidian
slate swan
#

ok

slate swan
#

oh

slate swan
# regal rapids im still so confused

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

lone flume
#

How do i do this?

lament mesa
#

!d discord.User.bot

unkempt canyonBOT
lone flume
#

How do i add it in my code?

slate swan
#

help me gaiz

slate swan
slate swan
lone flume
slate swan
lone flume
hasty iron
#

also server will be undefined

slate swan
hasty iron
#

?

slate swan
hasty iron
#

i did

#

you are missing an fstring

slate swan
#

wht should i define server with

hasty iron
#

Context.guild or Member.guild

#

you have both of those objects

slate swan
#

ohk thnx

hasty iron
#

use either one

lone flume
slate swan
hasty iron
#

you need a Context object

#

you have one

slate swan
slate swan
hasty iron
slate swan
#

its not working

slate swan
open brook
#

how to use bot object in help command

slate swan
#

just do you have been kicked in ctx.guild.name

open brook
#

in other cogs we can us it as self.client

slate swan
#

if you use self.client in cogs you should be able to use client without cogs

lone flume
lone flume
slate swan
pale turtle
#
    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?
lone flume
slate swan
slate swan
#

it's this you want

slate swan
vagrant brook
unkempt canyonBOT
#

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.

lament mesa
lone flume
pale turtle
lone flume
#

But theres no example..

slate swan
#

do you need one?

vagrant brook
#

It's a boolean

lone flume
slate swan
#

and what for

vagrant brook
#

Do you even need an example

slate swan
lament mesa
lone flume
# slate swan and what for
@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()
slate swan
hasty iron
#

what? open a pool everytime?

slate swan
#

Yes-

slate swan
hasty iron
#

what are "some errors"

hasty iron
#

it could've been on your end

slate swan
#

I don't remember but I'll try to reproduce it

slate swan
proven elm
#

Anyone got any project ideas thats the same difficulty as a discord bot?

hasty iron
#

hm

lament mesa
pale turtle
hasty iron
#

and you stored that connection

#

and used it everywehre

unkempt canyonBOT
#

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)```
slate swan
#

Wait did I say pool? notlikeblob Sorry I meant connection

pale turtle
hasty iron
slate swan
#

and use client.user

#

you haven't defined bot

lament mesa
lone flume
slate swan
#

bruh, i was giving you an example

lone flume
slate swan
#

don't copy paste, just try to understand..

slate swan
vagrant brook
#

Hmm

#

If you can't differentiate between a class and it's instance then probably you should go back and learn some python

lone flume
slate swan
#

bruh no

#

if p1 == client.user

pale turtle
#

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)```
vagrant brook
#

Like coming here to get spoonfed every single line of your code isn't a way to learn

lament mesa
#

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

slate swan
pale turtle
#

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)
river forge
#

How do I send a PM? I tried client.send_message() but it turns out that's deprecated, not sure what to use

slate swan
unkempt canyonBOT
#

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.
river forge
#

i've tried client.get_user(user).send(msg_), it gives me AttributeError: 'NoneType' object has no attribute 'send'

slate swan
#

it means get_user is returning None, that user id is not cached

river forge
#

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```
slate swan
#

huh, are you running the bot at all, what's preventing you from not just awaiting it

river forge
#

trying to run msg() synchronously

#

i'll try to rewrite it to run the stuff I want from the on_ready() event

slate swan
#

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)
lament mesa
#

id's are integers not strings

slate swan
#

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'
lament mesa
#

and on_ready does not take any arguments

slate swan
#

So what do I do?

river forge
slate swan
lament mesa
#

Context only gets passed into commands

slate swan
#

So I have to rewrite this?

late bolt
#

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?

slate swan
slate swan
fleet oracle
#

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

mortal gull
#

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?

rare saddle
#

How to use slash in cogs

manic wing
#

what module ae you using

rare saddle
#
from discord_slash import SlashCommand
proven elm
#

what are Cogs for?

late bolt
#

woah what does that module do?

limber cosmos
#

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```
dry kelp
#

How can i check if the author is in the same voice channel with the bot?

proven elm
#

Why is my bot sending the help section twice when I do .help

#

when I do .help it gives me the help commands twice

slate swan
proven elm
slate swan
#

okay, hmm

#

i see you are using cogs, do you have 2 on_message maybe?

cinder horizon
#

sends links will ju?

hasty iron
#

its on my profile

proven elm
#

cause it caused problems

opaque trail
#

is the bot being hosted twice somewhere?

#

perhaps you left a console open or something

proven elm
#

ive closed vs code but the bot is still online?

hasty iron
#

it doesn’t turn offline immediately

opaque trail
#

try using a command, it takes around 2 minutes until the bot changes the presence

limber cosmos
#

It usually takes a minute or two to reflect.

proven elm
#

awhhh its fixed now thanks

flint goblet
#

How to make a discord bot

#

Pls tell

flint goblet
#

Thanks @limber cosmos

full lily
flint goblet
#

Yes

full lily
#

muy bien

flint goblet
#

Pls English

full lily
#

very good :)

flint goblet
#

Thank you

#

Where do I should practice

#

For being better

fleet oracle
#

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)```
slate swan
#

oml please someone help me

opaque trail
#
        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

spring flax
slate swan
#

I'm coding a discord bot

#

with no coding experience whatsoever

#

and I've run into a problem

spring flax
opaque trail
fleet oracle
opaque trail
#

okay good luck

fleet oracle
fleet oracle
opaque trail
slate swan
fleet oracle
#

and the error

slate swan
# fleet oracle send the code

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))

slate swan
# fleet oracle and the error

Traceback (most recent call last):
File "main.py", line 4, in <module>
client = commands.bot(command_prefix = '.')
TypeError: 'module' object is not callable

opaque trail
#

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

fleet oracle
#

capital letters matter a lot

slate swan
#

oh lord I'm seeing that now

full lily
#

client doesn't support command features?

slate swan
#

is it fine if I post all the code here? it's only 50 lines

fleet oracle
#

``

opaque trail
fleet oracle
opaque trail
#

!code

unkempt canyonBOT
#

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.

full lily
#

right, right

slate swan
#

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'

opaque trail
#

yes but you should still delete the following line:

client = discord.Client()
slate swan
#

ok

opaque trail
#

and one more thing, in you ban and kick commands replace none by None and replace discord.member by discord.Member

slate swan
#

it worked!

#

omg ty

opaque trail
#

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

jade jolt
#

if you want to use on_message use @client.listen('on_message') instead

#

i hope thats right

opaque trail
#

uhh doesnt really matter but ok

jade jolt
#

it doesnt override the process_commands call

#

just a suggestion

opaque trail
#

oh it does? hmm, perhaps client.listen adds and event and client.event overrides the normal one

jade jolt
#

correct

slate swan
#

well where should I put await bot.process_commands(message)

plain egret
#
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

jagged root
#

Hey!! How do i make an event code only work if an specific user or role uses it.

plain egret
jagged root
#

Thanks.

plain egret
#

or

wicked atlas
jagged root
#

Thanks

#

too

vale pendant
#

Is the bot missing perms or the user?

plain egret
#
        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)
wicked atlas
plain egret
#

this should work in theory but in practise doesnt

vale pendant
#
if isinstance(error, commands.MissingPermissons)```
wicked atlas
#

ah yes

plain egret
#

then it should send this one

wicked atlas
#

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

plain egret
#
        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)
vale pendant
#

If the bot doesn't have permissions just add Bot in front of MissingPermissons in a elif statement.

plain egret
#

this handles if the author has perms

vale pendant
#

Yes.

#

BotMissingPermissons Handles if the bot is missing permissions.

plain egret
#

I will now try that, Thank you, my good sire!

wicked atlas
#

Ah. Yeah, you can tell I don't do much with error handling in discord.py

jagged root
# plain egret if ctx.message.author.id == "yourid": do something
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

vale pendant
#

Doesn't send the message?

plain egret
#

more info: this exception occurs when an admin tries to ban an admin with the same role order

jagged root
#

@plain egret were should i add it?

vale pendant
#

You have to check if the author has the same role as the user mentioned.

plain egret
#

no no

vale pendant
#
if ctx.author.top_role == member.top_role:
  return await ctx.send("You have the same highest role.")```
plain egret
#

oh

#

thanks.

vale pendant
#

Yeah.

jagged root
#

@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

plain egret
#

ritz

#

your solution worked!!

vale pendant
plain egret
#

thanks :)

vale pendant
#

Of course.

jagged root
vale pendant
#

A event?

jagged root
#

yes

#

an event

vale pendant
#

Hmmmm, you can possibly try grabbing the role then checking if the user has that role.

jagged root
#

idk how to do that

#

could you guide me

vale pendant
#
role = discord.utils.get(message.guild.roles, name="role")

if role in message.author.roles:
  # do something```
jagged root
#

Ok ill test it

jagged root
vale pendant
#

hmmm, isn't it message in your on_message event?

#

async def on_message(message)

jagged root
#

k

jagged root
# vale pendant `async def on_message(message)`
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

vale pendant
jagged root
#

true i didnt add : if role in message.author.roles:

#

yet

#

cause idk where

vale pendant
#

That doesn't matter yet.

jagged root
#

oh

vale pendant
#

So you want this event to be a certain role only?

jagged root
#

yea

vale pendant
#
@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.**"
            )```
jagged root
#

Thanks ill test it

jagged root
# vale pendant ```py @bot.listen("on_message") async def on_message(message): role = discor...
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```
vale pendant
#

fix message.guild.role to message.guild.roles my bad.

jagged root
#

alr np

stiff nexus
#
    @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
vale pendant
#

Wdym?

jagged root
vale pendant
#

Yeah, of course.

slate swan
#
    @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 ? ![PES_Think](https://cdn.discordapp.com/emojis/808622883847798804.webp?size=128 "PES_Think")
#

when using on_command is there a way to check what command was ran?

#

maybe a print statement at the end ?

maiden fable
jagged root
#

how i make so the bot deletes one message on an event

slate swan
#
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 ![pepesweat](https://cdn.discordapp.com/emojis/809664963953557524.webp?size=128 "pepesweat")
hasty iron
#

check is not defined

waxen granite
#

how do i define message for messages in a channel?

jagged root
#

how i make so the bot deletes one message on an event

slate swan
#

you mean channel.history?
@waxen granite

jagged root
#

only message that user sent

slate swan
jagged root
#

with await and didnt work

slate swan
#

what's the problem with it

jagged root
#
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()```
high flame
#

i guess you didn't define message

jagged root
#

and dont work

slate swan
#

just bot.listen

jagged root
high flame
#

you return

slate swan
#

and the function's name is gonna be the event

slate swan
#
@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
jagged root
#

confused

slate swan
#

and yeah

high flame
#

do you understand what return do?

jagged root
#

yes

high flame
#

then

jagged root
#

make the command dont work

slate swan
high flame
#

why you use it

jagged root
#

lol

#

o

high flame
#

ugh

jagged root
#

lol

slate swan
#

it leaves the function

jagged root
#

yea

high flame
#

remove the return before messsage.delete()

jagged root
#

thats what i meant

#

ok

slate swan
#

so message.delete() will be unreachable

#

bru

high flame
#

it return a value and the function stops

slate swan
#
@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
high flame
#

!e ```py
def x():
return "hello"

print(x())

unkempt canyonBOT
#

@high flame :white_check_mark: Your eval job has completed with return code 0.

hello
slate swan
#

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?

hasty iron
#

it is on point, doing *args makes it optional

slate swan
#

@slate swan it worked, thanks

slate swan
#

didn't know that

hasty iron
#

!e ```py
def foo(*args):
print(args):

foo()

#

oops

#

!e
def foo(*args):
print(args)

foo()

unkempt canyonBOT
#

@hasty iron :white_check_mark: Your eval job has completed with return code 0.

()
slate swan
#

this was so accidental lmao

waxen tangle
#

anyone got a list of colors u can use for an embed?

slate swan
#

!d discord.Colour

unkempt canyonBOT
#

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.
slate swan
#

fuk why cogs not work

#

lol

#

!d discord.ext.commands.Cog

unkempt canyonBOT
#

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.
jagged root
#

Delete function didnt work @slate swan could i send you the full code in dms

slate swan
#

send it here

#

the event

jagged root
#

i dont ppl copy it

#

you can answer me here

#

if you want

slate swan
#

people can make that alone

jagged root
#

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()```
jagged root
slate swan
#

so what exactly is the error?

jagged root
#

no error

#

it doesnt delete

#

but doesnt give a error

slate swan
#

does it delete the member's role

jagged root
#

yes

#

i want so it deletes the user message

#

when saying yes

slate swan
#

weird

jagged root
#

ik

#

im confused

#

too

slate swan
#

!d discord.Message.delete

unkempt canyonBOT
#

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.
slate swan
#

do you have the permission to do that?

jagged root
#

to do what

slate swan
#

delete messages

vale pendant
#

He doesn’t need permissions.

jagged root
#

only want to delete one message when using the event

#

only dat lmao

slate swan
#

you need the manage_messages for that

vale pendant
#

If you read it says “Your own messages could he deleted without any proper permissions”

slate swan
jagged root
#

only one message

vale pendant
#

He wants to delete the author message correct?

jagged root
#

purge one message

slate swan
#

yes, and the author is a member

#

not the bot

jagged root
#

i want to purge one message

#

only that

slate swan
#

I understand

jagged root
#

kk

vale pendant
#

Hmmm.

slate swan
#

do you have an error handler?

jagged root
#

it doesnt give an error

slate swan
#

answer the question

jagged root
#

No.

#

i ti think

#

anyways in the delete code it doesnt specify to delete 1 message

slate swan
#

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```
jagged root
#

huh

slate swan
#

since you specified the message in the event's parameters

jagged root
#

so what should i do

#

now

slate swan
# jagged root so what should i do

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

jagged root
#

i use to get errors but now i dont

#

in this code

slate swan
#
@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?

jagged root
#

or just delete 1 message

#

both could work

slate swan
slate swan
#
    await ctx.message.delete()```
#

on_message event

#

wawit

jagged root
#

?

slate swan
#

he did the right thing

#

he wants to delete the message sent by user after executing the command right ?

jagged root
#

fixed

#

im dumb

#

had to move the function one step above

slate swan
#

what

jagged root
#

cause code only worked if it had the role

#

and i added the function when it was already removed

slate swan
#

i was looking at another code and thought it was yours lmao

jagged root
#

i readed the code twice and noticed

slate swan
#

it doesn't actually ban the person

#

or work

#

he didn't provide a single error

slate swan
slate swan
#

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

slate swan
#

but I just come to realise

#

i did

#

you used @bot.command()

#

i dont use client

#

so you're not in a cog

vale pendant
#

Why did you put self?

slate swan
#

then why do you have a self arg

#

i think hes in a cog file aPES_Think

#

why

#

since hes using @commands.has_permission

#

and self

vale pendant
#

If he was in a cog he would use @commands.command

final iron
#

I think he may of copied it off a site like stack overflow

slate swan
#

maybe

vale pendant
#
  • why do you have message 1 message 2 and etc.
slate swan
#

how about we ask then aPES_Think

vale pendant
#

yes.

#
message3 = ctx.send(embed=embed1)
        sleeper=5
        await asyncio.sleep(sleeper)
        await message3.delete()
        return``` This is just a pain to look at.
slate swan
#

im not in a cog file

slate swan
#

remove self

slate swan
vale pendant
#

you can do await ctx.send(embed=embed, delete_after=3)

slate swan
vale pendant
#

you didn't put await in front of ctx.send.

slate swan
vale pendant
#

There's alot of errors.