#discord-bots

1 messages · Page 513 of 1

rustic venture
#

mhh

pliant gulch
#

It should be discord.Guild but here it says discord.guild

#

I'm assuming you imported guild which you shouldn't do

waxen granite
#

is there an event like on_message_edit for embeds?

slate swan
#

on_message_delete how get who delete the message?

rustic venture
pliant gulch
#

discord.Guild is the class

#

You want the instance of the class

#

Do not run methods directly on discord.Guild

slate swan
pliant gulch
#

It is possible, you will need to check the guilds audit logs

#

Although keep in mind if the messages author deleted the message it isn't audited

#

So check for that case

slate swan
pliant gulch
#

Yes it is

rustic venture
slate swan
pliant gulch
hasty iron
#

!d discord.Guild.audit_logs

pliant gulch
unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the guild’s audit logs.

You must have the [`view_audit_log`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") permission to use this.

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
slate swan
#

Ah I see

#

Thanks

slate swan
#

use await bans()

#

returns a list

hasty iron
#

well, you’re asking about js inside a python server, i don’t know what you expect

rustic venture
slate swan
rustic venture
#

there is no await bans xd

slate swan
#

oh I mean guild.bans()

#

you could do something like

@bot.command()
async def is_banned(ctx, user: discord.Member):
  guild = bot.get_guild(guild_id)
  bans = await guild.bans()
  banned = False
  for ban in bans:
    if ban == user:
      banned = True
  if banned == True:
    await ctx.send("Yes")
  else:
    await ctx.send("No")
pliant gulch
#

This wouldn't work

slate swan
#

why

hasty iron
#

!d discord.Guild.fetch_ban

unkempt canyonBOT
#

await fetch_ban(user)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves the [`BanEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.BanEntry "discord.BanEntry") for a user.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
pliant gulch
#

As guild.bans() returns a list of BanEntry objects

hasty iron
#

use that instead

rotund nova
#

some know why i have here problem?

pliant gulch
#

Not discord.Member objects

hasty iron
#

you seem to lack python knowledge

rotund nova
hasty iron
#

and basic at most

pliant gulch
#

And I'm unsure if you should be typehinthing discord.Member as if a member is banned they wouldn't be a member anymore

#

i.e causing a Not found error

#

Rather it should be typehinted to discord.User

hasty iron
rustic venture
#

yeah

slate swan
rotund nova
#

its ticket system

#

so users

hasty iron
#

you’re using json files

rotund nova
#

ya

hasty iron
#

which you shouldn’t be using

#

if you’re stuck on NameErrors, go back to basics

unkempt canyonBOT
#

class discord.BanEntry```
A namedtuple which represents a ban returned from [`bans()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.bans "discord.Guild.bans").
pliant gulch
#

Basically just an object that holds user and reason

slate swan
#

so you could do BanEntry.user to get the user, right?

rustic venture
#

am i to bad for understanding or is it so hard to write 1 line if a user is banned or not? idk i am to stupid for that so i ask here xd

slate swan
#

you're not stupid

#

never feel afraid to ask for help

rustic venture
#

you can call me this 1 line? ;D

pliant gulch
manic wing
#

andy

rustic venture
#

andy? you have an idea for this line?

manic wing
#

how can one force-put someone on a cooldown

#

commands.cooldown buckettype.user

slate swan
#

hello!

#

i have this code. but the logschannel thing doesnt work. i mean yeah it sends the message but like this

#

my code is

#
    elif self.values[0] == '🚑E.K.A.B':
      await interaction.channel.delete()
      guild = interaction.guild
      user = interaction.user
      name = 'applications'
      logschannel = interaction.guild.get_channel(893915900531605504)
      message = interaction.message
      category = discord.utils.get(interaction.guild.categories, name=name)
      channel = await guild.create_text_channel(f'🚑E.K.A.B Application', category=category)
      await channel.set_permissions(interaction.guild.default_role, send_messages=True, read_messages=False)
      await channel.set_permissions(user, view_channel = True)
      await channel.set_permissions(guild.default_role, connect = False, view_channel = False)
      await channel.send(f"{user.mention}")
      wres = discord.Embed(title="Πόσες ώρες έχετε στο FiveM?", description="", color=orange)
      steam = discord.Embed(title="Ποιό είναι το Steam Name σας?", description="", color=orange)
      disc = discord.Embed(title="Πόιο είναι το Discord Name σας?(μαζί με το #)", description="", color=orange)
      onoma = discord.Embed(title="Ποιό είναι το όνομά σας?", description="", color=orange)
      close = discord.Embed(title="H αίτησή σας στάλθηκε με επιτυχία!", description="Το channel θα κλείσει αυτόματα σε 30 δευτερόλεπτα!", color=orange)
      await channel.send(embed=onoma)
      def check(m):
          return m.channel == channel
      
      awnser = message
      msg = await client.wait_for("message", check=check)
      await channel.send(embed=wres)
      def check(m):
          return m.channel == channel

      awnser2 = message
      msg = await client.wait_for("message", check=check)
      await channel.send(embed=steam)
      def check(m):
          return m.channel == channel

      awnser3 = message
      msg = await client.wait_for("message", check=check)
      await channel.send(embed=disc)
      def check(m):
          return m.channel == channel

      awnser4 = message
      msg = await client.wait_for("message", check=check)
      await channel.send(embed=close)
      res = discord.Embed(title=f"Νέα αίτηση Ε.Κ.Α.Β απο τον {user.name}",description="", color=orange)
      res.add_field(name = 'Ποιό είναι το όνομά σας?', value=f"`{awnser}`", inline = True)
      res.add_field(name = 'Πόσες ώρες έχετε στο FiveM?', value= f"`{awnser2}`", inline = True)
      res.add_field(name = 'Ποιό είναι το Steam Name σας?', value= f"`{awnser3}`", inline = True)
      res.add_field(name = 'Πόιο είναι το Discord Name σας?(μαζί με το #)', value= f"`{awnser4}`", inline = True)
      await logschannel.send(embed=res)
      await asyncio.sleep(30)
      await channel.delete()
placid skiff
#

there is a way to check if the bot is mentioned without using on_message event?

fallow mauve
#

im trying out a thing where i want the user to say ";hello" and the bot reply "Hi! How are you?", and if the user replies with "good" it replies with "Good! Me too." but if not it gives a different response, how does that work?

kindred epoch
fallow mauve
#

can u give an example of how that would go into the code?

placid skiff
sage fossil
#

I have a command that you use on a member, how would I make a cooldown so the member that used the command cannot use it on the member they used the command on for a certain amount of time

kindred epoch
unkempt canyonBOT
#

wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
kindred epoch
#

go to the link, it has examples of how to use wait_for

placid skiff
#

Why this doesn't work? it send me only the second message (DM only) but it runs trough the first one cuz it print me the prefix in the console

kindred epoch
kindred epoch
#

!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.

sage fossil
sage fossil
#

I want it to work if the bot goes offline though

kindred epoch
#

i cant think of anything else

kindred epoch
sage fossil
#

So if it goes online again it'll still be on cooldown

#

If the cooldown ya know

kindred epoch
#

yea use asyncio.sleep

sage fossil
#

Hasn't passed

kindred epoch
#

i cant think of anything else at this time

#

so might just use your own brain and find an idea of how to do it

sage fossil
#

I tried

placid skiff
# kindred epoch can you copy and paste the code? sending an image makes it harder to know whats ...
@Envenom.listen('on_message')
async def message_event(message: Message):
    if message.author == Envenom.user:
        return

    if message.content == Envenom.user.mention:
        if message.guild is not None:
            pref = db.field("SELECT Prefix FROM Guilds WHERE GuildID IS ?", message.guild.id)
            await message.channel.send(f"Il mio prefisso qui è {pref}\n"
                                       f"Usa {pref} help per saperne di più")
        else:
            await message.author.send(f"Il mio prefisso è {Envenom.prefix}\n"
                                      f"Usa {Envenom.prefix} per saperne di più")
    else:
        return
kindred epoch
#
await message.channel.send(f"Il mio prefisso qui è {pref}\n"
                                       f"Usa {pref} help per saperne di più")
``` and idk what you're trying to do here
placid skiff
#

sqlite3

#

I'm trying to send a message to the channel where the message was sent

#

I think that is more confusing now lol

kindred epoch
#

?

#

do you know how .send works?

placid skiff
#

I'm trying to respond to a message to the channel where that message was send

placid skiff
kindred epoch
#

you cant have two of "" in 1 .send

placid skiff
#

Those are the same lines, i used them a lot lol, if you check they share the same parenthesies

#

they aren't two different messages, is the same send written in two lines

kindred epoch
#

wait nvm

placid skiff
#

Cuz PyCharm throws warning if the line exceed a certain value and warnings triggers me D_D

placid skiff
kindred epoch
#

idk what kind of sql uses db.field

placid skiff
#

LOL i found the error

#

Nope, just confused D_D

#

Wait no, actually there is something strange

#
if message.content == Envenom.user.mention
#

In this line, message.content contains the bot mention

#

it starts with a !

#

in the message.content

#

changed in

if message.content.strip("!") == Envenom.user.mention:
placid skiff
final iron
#

Is there a way to see how many lines the bot is sending in a message or add a cap to how many lines it will send?

placid skiff
#

what u mean for lines?

final iron
#

Im creating an eval command I would like to cut it off after a certain amount of lines of text

placid skiff
#

U can turn the content to a list by using split method

from nextcord.ext.commands import Context, command

@command()
async def echo(ctx: Context, *, message):
   message = message.split(" ")
   await ctx.send(message)

this will send a list that contains all words in the message

final iron
#

How would this help me cut the lines off at a certain point though?

placid skiff
#

Ever used slicing with lists?

lst = ["a", "b", "c", "d"]

print(lst[1:-1]

will print b, c

final iron
#

I've never used splicing with lists only with strings

placid skiff
#

u can use it with lists to, it's pretty the same

If the list contains string, u can slice the string directly from the list, ex:
lst[3:][-1] slice the element in the list from the third element and select only the last word

final iron
#

Doesnt doing that only split a specific amount off the end?

placid skiff
#

?

final iron
#

I'm trying to make it so it splits up until a point. Like I enter in a certain line in the code and then any line after that gets cut off

#

For example no matter how many lines the bot sends it will always cut off at line 12

placid skiff
#

Well yes, slicing does this lol

There is another method tho, however it needs to turn the string to a list too. using for loop, send only the words u want to send from that list (so for word in range(your_range): ctx.send(message[word])

#

Or you can pop all the element of the list from the index u want to

#

Btw slicing is the best way in my opinion

final iron
#

I will try it out

stoic geode
#

Hello i'm not really good with python and i've been wanting to make a discord bot that sends a timed message in an est time zone but i'm not sure how

placid skiff
#

Well that is not a simple thing to do for python beginners

U can do it by using tasks to make the bot do something every tot time or do it by using time package

For the tasks u can check some tutorial on youtube, there are plenty (search for discord.py tasks)

For the other one you need to study more python

heavy heath
#

Does anyone know if i can make a command that would force the bot to leave the server ive given? for example !forceleave (server name or ID).

slate swan
#

how can i make my atheon bot have an implementation where it browses for the most relivant user via username alphabetical order and role name via alphabetical order like dyno? is that possible with dpy?

placid skiff
placid skiff
#

U wait now i understand

slate swan
placid skiff
# slate swan so basically it takes the argument ive given, being "t" and "m", and matches it ...

I try to explain it in a simple way

Of course you need member and role intents enabled to do this
First, get the list of all the members in a Guild (make sure to get the members.name), do the same thing for roles
Next, u need to save in a list all the member that has the argument given in the list, same thing for roles
Then u sort the list and convert the first element of the list into a member object and a role object, then change the role as you do normally

#

I hope that is clear enough

final iron
#

@placid skiff Your method didn't work. Let me try and explain what im looking for better. So lets say I did this. for i in range(20): print("test"). The result would end up taking 20 lines. What I want is so that no matter how many lines it is ie the range it would always only send the first 12 lines and nothing else.

placid skiff
slate swan
placid skiff
#

!e

lst = ["test1", "test2", "test3", "test4", "test5"

print(test[2:-1] )
#

Uhm i ha e to check this better

final iron
#

You are forgetting a [

placid skiff
#

Lol

final iron
#

!e

lst = ["test1", "test2", "test3", "test4", "test5"]
print(test[2:-1])
unkempt canyonBOT
#

@final iron :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | NameError: name 'test' is not defined
final iron
#

shit

placid skiff
#

I'm tired xD, sorry

final iron
#

!e

lst = ["test1", "test2", "test3", "test4", "test5"]
print(lst[2:-1])
unkempt canyonBOT
#

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

['test3', 'test4']
placid skiff
#

So see? It cuts the first two element and the last one

final iron
#

Yes I know

#

But lets say I add more elements onto it

#

!e

lst = ["test1", "test2", "test3", "test4", "test5", "test6"]
print(lst[2:-1])
unkempt canyonBOT
#

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

['test3', 'test4', 'test5']
final iron
#

Now it is showing test5

placid skiff
#

Change the -1 with 4

final iron
#

Basically what I am looking for is that no matter how many elements I add on

placid skiff
#

Remember, slicing is:
variable[start: end: step]

final iron
#

It will only ever send "test3" and "test4"

placid skiff
#

If you want it to change then use variables lol

final iron
#

Wdym

placid skiff
#

!e

lst = ["test1", "test2", "test3", "test4", "test5"]
a=2
b=4

print(test[a:b] 
final iron
#

!e


lst = ["test1", "test2", "test3", "test4", "test5"]
a=2
b=4
print(test[a:b])
unkempt canyonBOT
#

@final iron :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 4, in <module>
003 | NameError: name 'test' is not defined
final iron
#

!e


lst = ["test1", "test2", "test3", "test4", "test5"]
a=2
b=4
print(lst[a:b])
unkempt canyonBOT
#

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

['test3', 'test4']
placid skiff
#

I missed a parenthesies again lol

#

So change a to 1 and b to 5 it will print from 2 to 5

final iron
#

Could I do a:b:c?

#

If I defined c?

visual island
#

sure

placid skiff
#

The last one is step, it will step to your list

visual island
#

it will step the slicing process

placid skiff
#

!e

lst = ["test1", "test2", "test3", "test4", "test5"]

print(test[::2 )
#

I can t do this lol

visual island
#

!e

lst = ["test1", "test2", "test3", "test4", "test5"]

print(lst[::2]) 
placid skiff
#

Now i feel myself a bad programmer xD

final iron
#

!e

lst = ["test1", "test2", "test3", "test4", "test5"]
print(lst[::2])
unkempt canyonBOT
#

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

['test1', 'test3', 'test5']
#

@visual island :white_check_mark: Your eval job has completed with return code 0.

['test1', 'test3', 'test5']
visual island
#

you can

placid skiff
pliant gulch
#

Why are you doing string slicing if you want to restrict newlines

#

Do you know you can count the newlines in a string

final iron
#

Nope

#

Thats what I was looking for in the first place

visual island
#

wait, what are you trying to do?

pliant gulch
#

!e ```py
my_string = "a\nb\nc"
print(my_string.count("\n"))

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

2
pliant gulch
#

Then compare this number to a limit you set

#

No point in all this useless string slicing

#

And with string slicing it won't be consistent

final iron
visual island
#

oh

#

use andy's example code then

final iron
#

alr

#

There are no physical \n's in my code though

pliant gulch
#

It should pop up as \n everytime a newline appears

#
In [1]: a = """
   ...: aaaaaaa
   ...: bbbbbb
   ...: cccccc
   ...: """

In [2]: print(a.count("\n"))
4

In [3]:
final iron
#

I still don't understand how im supposed to end up deleting all the lines after the limit

placid skiff
#

Just don t send them

visual island
#

firstly count the "\n" then see if it's > than the limit, then delete it

final iron
#

Wait

#

So basically for my eval command I send the executed code to a file. Then read the file and send it. Wouldn't there be some easier way to remove the lines since im doing it that way?

placid skiff
#

Why u are sending the code to a file?

Can you paste the code?

final iron
crystal wind
#

Is anyone familiar with FFMPEG with discord bots?

final iron
#

I can send the code but its really quit straight forward

placid skiff
final iron
placid skiff
#

Nope

hot cobalt
#

@final iron Why not utilise what we've made for our bot, it's open source

#

And safe

hot cobalt
#

Ok, just make sure you make it safe

final iron
#

Its only for me

#

And probably some friends I can trust

hot cobalt
#

I would still hesitate to implement that, what if a friends or your account gets hacked, what if you accidentally run something etc etc

crystal wind
#

So I have a little issue with my join command with my bot. What I did here is making my bot play an mp3 audio file that I've stored in my disk locally, using FFMPEG. Although this works, every time I summon her, this message appears in the console, saying I haven't really defined the properties of the FFMPEG or something like that.

What I wish to do is to make this message gone to avoid my console to be spammed. What should I do?

slate swan
#
--> python3 -m poetry add bs4
Using version ^0.0.1 for bs4

Updating dependencies
Resolving dependencies...

  AttributeError

  __enter__

  at /opt/virtualenvs/python3/lib/python3.8/site-packages/poetry/utils/helpers.py:98 in download_file
       94│     url, dest, session=None, chunk_size=1024
       95│ ):  # type: (str, str, Optional[requests.Session], int) -> None
       96│     get = requests.get if not session else session.get
       97│ 
    →  98with get(url, stream=True) as response:
       99│         response.raise_for_status()
      100101with open(dest, "wb") as f:
      102for chunk in response.iter_content(chunk_size=chunk_size):
exit status 1


Replit: Package operation failed.
#

cant do from bs4 import BeautifulSoup

#

anyone know why?

final iron
#

I also couldn't find the file if I tried. The bots github is like a literal maze

pliant gulch
#

!source eval

unkempt canyonBOT
#
Command: eval

Run Python code and get the results.

Source Code
pliant gulch
#

Thats the one

final iron
#

Tbh I don't understand it much

#

Back to my semi original question. Since I send my executed code to a file and then send the contents of the file on discord is there a way to make it send only a certain amount of lines?

#

I got given a solution to this

#

But since im not just capturing it in a variable I think there could be an easier way to do it

viral prawn
#

elif str(rctn) == '❌':

#

Does anyone know why I get syntax error?

rich mirage
maiden fable
maiden fable
rich mirage
maiden fable
#

Welp, can't find the link. Gimme 1

rich mirage
crystal wind
#

anyone familiar with FFMPEG? not youtube related btw

rich mirage
maiden fable
#

Install dpy from master

rich mirage
maiden fable
#

pip install -U git+https://github.com/Rapptz/discord.py

#

Install this from bash

flint forum
#

bruh

slate swan
maiden fable
#

?

flint forum
#
@bot.event()
@has_permissions(administrator=True)
async def on_member_join(ctx, member):
    channel = bot.get_channel(894022807892164608)
    welcomeembed = discord.Embed(title= 'Welcome to the server!' + ' f"{member}' , description= 'Test 1')
    welcomeembed.set_thumbnail(url='https://i.imgur.com/s3PooTk.png', )
    await channel.send(embed=welcomeembed)
    time.sleep(10)
    await bot.delete_message(messages)```
maiden fable
flint forum
#
    @bot.event()
TypeError: event() missing 1 required positional argument: 'coro'```
rich mirage
slate swan
#

ive used it once for testing my code but that was along time ago

maiden fable
flint forum
#

i dont need ()?

slate swan
#

and remove the context arg

rich mirage
final iron
flint forum
#

i dont know

#

that was on accident lol i was speeding

final iron
#

Also why are you using concatenation with an f string

flint forum
#

Yeah i need help with that

#

I don't know how to send a members @ in an embed

#

in the title

slate swan
#

the string on the member isnt right the first one is " and the second one is '

flint forum
#

ah

final iron
#

Just doing that wont mention them

slate swan
#

yes you have to member.mention

final iron
#

I don't think that will work either

#

Because title

flint forum
#

I don't rly wana mention them

#

I just wana put there user with the @

final iron
#

I haven't tested it but ctx.author.mention wont work in the title

flint forum
#
@bot.event
async def on_member_join(ctx, member):
    channel = bot.get_channel(894022807892164608)
    welcomeembed = discord.Embed(title= 'Welcome to the server!' + f'{member}' ,
    description= 'Welcome to the server buddy')
    welcomeembed.set_thumbnail(url='https://i.imgur.com/s3PooTk.png', )
    await channel.send(embed=welcomeembed)
    asyncio.sleep(10)
    await bot.delete_message(messages)```
slate swan
flint forum
#

this is my code rn but it aint workin

slate swan
#

remove ctx arg

flint forum
#

where

#

ohh i see..

slate swan
#

on_member_join takes only member argument

#

also you might want to await asyncio.sleep(10)

final iron
flint forum
#

ill define it

final iron
#

Also don't use concatenation just use an f string

slate swan
#

but bot doesnt have any attributes to delete_message

flint forum
#

member: discord.Member will do correct

final iron
#

For an on_member_join

flint forum
#

oh just leave it then?

#

alr

final iron
#

member does the same as member: discord.Member in this situation

flint forum
#

mhm

boreal ravine
#

^

heavy radish
#

Heyy, I was wondering how I can do this. So the command would be like !g <User> <Role set by a number> <Message> How do I assign a role to each number. Like 1 = @tt1 2 = @tt2

#
@bot.commands()
async def g(ctx, member: discord.Member, int, *, arg):
  1 = 
#

My current attempt....

flint forum
#

What do you suggest I do for the delete message part

boreal ravine
slate swan
#

what message are you even trying to delete?

flint forum
#

in py await bot.delete_message(messages)

final iron
#

What are you trying to delete?

flint forum
#

the message itself

#

destroy itself

boreal ravine
#

the welcome message?

flint forum
#

after the awaited 10 seconds

#

yeah the whole message the bot sends

slate swan
#

then await message.delete() define message to the message you sent

boreal ravine
#

use the delete_after kwarg and set it to an int on the line u sent the message

slate swan
#

or that

boreal ravine
#

yes

flint forum
flint forum
#

huh

maiden fable
#

!d discord.abc.Messageable.send @boreal ravine

unkempt canyonBOT
#

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
boreal ravine
#

hmmm

maiden fable
#

It's an abstract class, hence abc

heavy radish
flint forum
#
@bot.event
async def on_member_join(member):
    channel = bot.get_channel(894022807892164608)
    welcomeembed = discord.Embed(title= 'Welcome to the server!' + f'{member}',
    description= 'Welcome to the server buddy')
    welcomeembed.set_thumbnail(url='https://i.imgur.com/s3PooTk.png', )
    await channel.send(embed=welcomeembed)``` even without the delete part it wouldn't work
boreal ravine
maiden fable
rich mirage
boreal ravine
boreal ravine
heavy radish
maiden fable
maiden fable
flint forum
#

@boreal ravine py @bot.event async def on_member_join(member): channel = bot.get_channel(894022807892164608) welcomeembed = discord.Embed(title= 'Welcome to the server!' + f'{member}' , description= 'Welcome to the server buddy') welcomeembed.set_thumbnail(url='https://i.imgur.com/s3PooTk.png', ) await channel.send(embed=welcomeembed, delete_after=10)

#

I am going to recieve no errors but something is wrong

#

I don't get any results

slate phoenix
#

You probably don’t have member intents enabled

maiden fable
#

!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.

slate phoenix
#

!d discord.Intents

maiden fable
#

Lol

heavy radish
boreal ravine
# rich mirage docs say flagconverter is new in v 2, discord py is at a.1.7.x ?

How to install Discord.py 2.0.0
Simple go to shell/command promt and type in pip install -U git+https://github.com/Rapptz/discord.py You do need to install git first, for more info plea!se read this link to learn how to install git to your path
https://github.com/git-guides/install-git

GitHub

An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.

GitHub

Learn how to install git.

#

oop

maiden fable
#

pip install -U git+https://github.com/Rapptz/discord.py

Run this, ezzz

boreal ravine
#

git install 2.0

flint forum
#

Ayy @boreal ravine cheers it works great but is there a way to make it more asthetic

slate swan
heavy radish
flint forum
#

Because the message is so small

boreal ravine
unkempt canyonBOT
#

@boreal ravine :white_check_mark: Your eval job has completed with return code 0.

works lol
flint forum
#

But everything works good even the delete after

slate swan
#

ok

maiden fable
flint forum
#

I just need to make it bigger tbh

slate swan
heavy radish
maiden fable
heavy radish
#

Ye

flint forum
#

What can I do to make the embed message bigger

heavy radish
#

Done

#

What about role_dict?

final iron
flint forum
#

great idea loll

boreal ravine
boreal osprey
#

the event is not working

@bot.event
async def on_member_join(ctx, member):
    channel = bot.get_channel(738540358983745652)
    emb=discord.Embed(description = f'Welcome to the server {member}!', color = discord.Colour.random())
    emb.set_thumbnail(url=member.avatar_url)
    await channel.send(embed=emb)
slate phoenix
unkempt canyonBOT
#

class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
boreal ravine
#

@boreal osprey intents?

boreal osprey
boreal ravine
#

ye

#

!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.

flint forum
#

What's the thingy that shows the @ and not like Flashy#6969

flint forum
#

its like ctx.author something

boreal osprey
flint forum
#

yes mention

boreal osprey
#

how do i import all intents?

final iron
flint forum
#

Ik

#

How would I make a text that sends there @ only above the embed

#

Just the @ nothing else

#

perhaps using ctx would work

boreal ravine
final iron
slate phoenix
flint forum
#

Yes

boreal ravine
#

hm

heavy radish
#

Forget the arg1

flint forum
#

anyone mind joining a server to test it for me u can leave after

boreal ravine
#

make the dict first?

flint forum
#

If I'm allowed to ask that question that is.

boreal ravine
#

u cant append something to a dict before it was made i think?

flint forum
#

Alright I'll dm you.

heavy radish
#

What should I do then?

flint forum
flint forum
#

Don't got an alt rn so

heavy radish
#

Imagine not having 5 ALTs

boreal ravine
#

wait my wifi is acting up

flint forum
#

np

boreal osprey
#

i got a error now

boreal ravine
#

errors? @flint forum

flint forum
#
    await channel.send(f"{member.mention}",embed = embed)
NameError: name 'embed' is not defined
#

Should I just add it to welcomeembed

final iron
boreal ravine
#

in the ()'s

flint forum
atomic topaz
#

I'm making a welcoming function for my bot and wanna check if someone joined the server but I don't know how to do it with discord.ext (that bot one)

boreal osprey
#

but it's alr there

boreal ravine
#

hm

boreal ravine
#

ctx is for commands only

boreal osprey
#

k

#

i remove

final iron
boreal ravine
#

yes

heavy radish
flint forum
#

why'd it send too

boreal osprey
#

yay it works :D

flint forum
#

two

boreal ravine
flint forum
#

huh

#

its running more then once?

boreal ravine
final iron
boreal ravine
# flint forum its running more then once?

Is your bot responding twice? Well there are billions of reasons for that:

  • Multiple process_commands
  • Multiple ctx.invoke
  • Incorrect subclassing ctx
  • Running two instances
  • Your token getting compromised

Happy figuring out the reason from the following!

flint forum
#

lol

#

Alr im sorry jus 1 more try :). @boreal ravine your rly helpful btw

boreal ravine
#

channel is a variable to send to certain channels tho

#

and its an event

#

so it wont be invoked

final iron
boreal ravine
#

o

final iron
#

Actually yeah he defined channel

boreal osprey
#

if your bot is sending two things at once, i'm pretty sure check your events and add await bot.process_commands(what ever is in these paranthesis)

final iron
#

So there is a point

boreal ravine
#

hm

flint forum
#

nope its not that the bot is running 2 instances

#

token isnt comprimised

#

mulitple ctx.invoke nope

boreal ravine
#

is ur bot on another site or something?

flint forum
#
@bot.event
async def on_member_join(member):
    channel = bot.get_channel(894038356814598145)
    welcomeembed = discord.Embed(title= 'Welcome to the server! ' + f'{member}' ,
    description= 'Welcome to the server buddy')
    welcomeembed.set_thumbnail(url='https://media.giphy.com/media/3o6ZtpxSZbQRRnwCKQ/giphy.gif', )
    await channel.send(f"{member.mention}",embed = welcomeembed)
    await channel.send(embed=welcomeembed, delete_after=10)```
#

code ^

#

Na my code on pycharm

boreal ravine
#

the code/token*

flint forum
#

okay

final iron
flint forum
#

huh

flint forum
#

I did

boreal ravine
#

u have 2 await channel.send's

#

use 1

boreal osprey
#

oh yeah

flint forum
#

but the other wouldn't work eh

boreal ravine
boreal ravine
final iron
heavy radish
# final iron Btw you don't have to name the args `int` and `arg`. They can be named whatever ...

Could You check this?

@bot.command()
async def g(ctx, member: discord.Member, role_dict, *, arg):
  guild = ctx.guild
  role = ctx.role
  channel = bot.get_channel(886837547328761868)
  role_dict.append({0: "Shhh...Slient Giveaway", 1: guild.get_role(892037663614435398), 2: guild.get_role(892037707491061840), 3: guild.get_role(892037725589479484)})
  role_dict = {0: role-object, 1: role-object, 2: role-object, 3: role-object}
  await channel.send(f"{role_dict} \n **__Host:__** <@{member}> \n **__Requirement:__** {arg} \n \n **__Helpful Staff:__** {ctx.author.mention}")
flint forum
#

how about this

@bot.event
async def on_member_join(member):
    channel = bot.get_channel(894038356814598145)
    welcomeembed = discord.Embed(title= 'Welcome to the server! ' + f"{member.mention}" ,
    description= 'Welcome to the server buddy')
    welcomeembed.set_thumbnail(url='https://media.giphy.com/media/3o6ZtpxSZbQRRnwCKQ/giphy.gif', )
    await channel.send(embed=welcomeembed, delete_after=10)```
#

oh wait it still wouldn't ping outside

boreal ravine
boreal ravine
flint forum
#

my problem with py is where to put stuff that i never used before

final iron
boreal ravine
heavy radish
zealous berry
#

How to make it so that the random choice variable (spells) is the same as the message the user types in? I’m coding a discord bot, and this is my code:

Spells is the message variable, and spellpot is the list of words the user needs to type in, but if the user types in something else that is in the spellpot it still works, how to make it specific to one?

    mesag = await message.channel.send(random.choice(spells))
    def check(m):
      return m.content in spellpot and m.author == message.author
final iron
#

Just makes it easier for me to read

zealous berry
zealous berry
#
if message.content.lower().startswith(("cat game", "Cat game", "CAT GAME")):

    channel = message.channel
    await message.channel.send("you are the cat. your aim is to defeat the dragon using 3 spells!")
    await asyncio.sleep(3)
    spellpot = ["defeat the dragon now", "sleeping by the river", "sleep dragon sleep now"]
    spells = ["quick, the dragon is asleep! type in `defeat the dragon now` to use your potion on it!", "look!! the dragon is sleeping! quickly type `sleeping by the river` to make it sleep!", "what's that sound? it must be the dragon snoring... type in  `sleep dragon sleep now` to keep it sleeping!"]
    awake = ['uh oh, the dragon woke up and defeated you. try again?', 'RAAWWRRR!!!!!! the dragon has woken up and defeated you-', 'oh no, the dragon defeated you...']
    mesag = await message.channel.send(random.choice(spells))
    def check(m):
      return m.content in spellpot and m.author == message.author

    try:
      msg = await client.wait_for('message', timeout=4.0, check=check)
    except asyncio.TimeoutError:
      await message.channel.send(random.choice(awake))
      return
    else: 
      await channel.send('good hit! you used your sleeping potion on the dragon, it now sleeps for longer!')

It’s kind of like a game thing

slate swan
#
 if not message.guild.id in blacklist:
    	if message.content.lower()=="blank":
      	  messages=[f"{message.author.name}, you say? Blank is a python-based discord bot developer (Beginner). Still he makes good stuff.", 'People say "He is still online."', "Blank is the hope of the future!", "I like Blank :3", "Hehe, What you wanna ask him??", "Blank is the secret of my energy!", "Hail Blank!", "Blank! Someone is calling you :D", "Blank is mine! Don't you dare touch him 😡"]
         if not message.author.id == owner_id:
                    reply= random.choice(messages)
               	 webhook = await message.channel.webhooks()
               	 webhook = utils.get(webhook, name = "Embed Bot")
               	 if webhook is None:
                    	webhook = await message.channel.create_webhook(name = "Embed Bot")```
#

Please help

zealous berry
#

It says indent error

final iron
#

its obvious

slate swan
#

Yea just saw srry

final iron
#

So you sent the error here before even reading it?

slate swan
slate swan
#

Because its 7:30 and I cant access my pc rn

final iron
zealous berry
rich mirage
#

code does nothing :/

boreal osprey
rich mirage
#

i am using the code for flagconverter but it does nothing with the two commands that i shared after it, please advice / hint

zealous berry
#

What is the command supposed to do

rich mirage
#

just respond "working"

#

as in that it got triggered

zealous berry
#

Do you need the flags?

rich mirage
#

yes i do, i will work on that part too once the command triggers

slate swan
zealous berry
#

You need a prefix right

rich mirage
#

ok checking

zealous berry
#

I don’t think commands.command will work, try client.command

zealous berry
slate swan
#

Now I am getting inconsistent use of tabs and spaces error but I haven't used tabs

marsh dove
slate swan
zealous berry
slate swan
marsh dove
#

oh shoot

zealous berry
#

Oh ye but the article said but I’m still using it

marsh dove
#

and i though discord.py was made by discord themselves

atomic topaz
slate swan
#
 if not message.guild.id in blacklist:
    	if message.content.lower()=="blank":
      	  messages=[f"{message.author.name}, you say? Blank is a python-based discord bot developer (Beginner). Still he makes good stuff.", 'People say "He is still online."', "Blank is the hope of the future!", "I like Blank :3", "Hehe, What you wanna ask him??", "Blank is the secret of my energy!", "Hail Blank!", "Blank! Someone is calling you :D", "Blank is mine! Don't you dare touch him 😡"]
        if not message.author.id == owner_id:
               reply= random.choice(messages)
               webhook = await message.channel.webhooks()
               webhook = utils.get(webhook, name = "Embed Bot")
               if webhook is None:
                   webhook = await message.channel.create_webhook(name = "Embed Bot")
               embed = discord.Embed(description=f"**{reply}**", colour= discord.Colour.random())
               await webhook.send(username="OwO", avatar_url="https://cdn.discordapp.com/avatars/408785106942164992/4844cebae2d84d63254ce5e383709a46.webp?size=80", embed=embed)               
   
    await client.process_commands(message)```
marsh dove
#

you coding from a phone yert

slate swan
#

Because I cant access pc right now

zealous berry
slate swan
#

Nah I checked

#

Wait

zealous berry
#

The reply=

slate swan
#

I don't think sticking = with variables affect the program at all

boreal ravine
zealous berry
slate swan
#

I fixed it but still error

hexed swallow
slate swan
brazen seal
#

how i can fix this error?

slate swan
#

Send code with error

brazen seal
slate swan
#

Sorry no experience with cogs

heavy folio
#

hi, im making a slash command with discord-py-slash-command (pypi), but when i tried /, my bot's name wasnt there, but i already made a slash command, theres no errors

slate swan
#
  for member in ctx.guild.members:
    try:
      print(member)
    except:
      print('a')

tf this is only printing one time

boreal ravine
#

member

#

will print

#

their

#

tag

slate swan
#

thats not my problem lmao

#

it only loops once

boreal ravine
#

hm

marsh dove
#

are there more members in the server?

boreal ravine
#

@slate swan noob

slate swan
slate swan
#

it wont do that for my shit

boreal ravine
#

@slate swan does it have intents

boreal ravine
#

hm idk then

#

@slate swan errors?

brisk fiber
brisk fiber
#

np

heavy folio
#

i thought i did something wrong

#

wait how do i make it one guild only

brisk fiber
#

nope, just discord’s issue haha

boreal ravine
#

guild id param

brisk fiber
#

uhhh i think you send the request to a different url— check the documentation

boreal ravine
#

check the lib's docs

#

or github

brisk fiber
#

oh yeah you’re using a library

brazen seal
#

Someone can help with this?

heavy folio
#

yeah okay ty

heavy folio
boreal ravine
heavy folio
#

eh wait i tried doing guild_ids=[myID] but it didnt show up, even refreshed my discord multiple times, and the bot does have perms and so do i, both of us have admin

slate swan
#

how can i check if a message is an embed

grim oar
#

!d discord.Message.embeds

unkempt canyonBOT
grim oar
slate swan
slate swan
grim oar
#

are you using a command or event

slate swan
#

event

grim oar
#

Which one

slate swan
#

on_message

flint forum
#

How do I show a users name in the title like Flashy#6969 (title of an embed)

flint forum
slate swan
flint forum
#

k thx

slate swan
solemn grove
#
embed.set_thumbnail(url=ctx.discord.Guild.icon_url)

Why it's giving error?

final iron
#

Whats your issue

#

Whats the error?

crystal wind
#

Concerning about commands with on_message(message)
I was wondering if you could verify a list of keywords that contains in message.content.

maiden fable
#

!d discord.ext.commands.Command

unkempt canyonBOT
#

class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.
crystal wind
#

Ye I don’t have the command with me rn because im not on my pc rn. Let me try to remember it.

#

Hold on gimme a few mins

maiden fable
#

Okay?

#

Which command do u want?

#

@bot.command() u talking about?

crystal wind
#

uhhh it’s on_message(message) I think it’s @client.event

#

Lemme check

maiden fable
#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
maiden fable
#

Don't specify the channel....?

#

only specify the self_deaf kwarg, nothing else?

#

Ah

#

!d discord.Guild.change_voice_state

unkempt canyonBOT
#

await change_voice_state(*, channel, self_mute=False, self_deaf=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Changes client’s voice state in the guild.

New in version 1.4.
maiden fable
#

Hmm okay

#

Well, idk. Sorry dude

crystal wind
#

response.amongus = [list of among us keywords] response.amongus_reply = [list of among us replies such as "STOP"] async def on_message(message): if **response.amongus** in message.content: await channel.send(random.choice(response.amongus_reply))

This doesn't work for a list, it has to be a string like quoted to work. I was wondering if there's a way for it to add more than one keyword for the same purpose.

#

What's in stars is not working.

maiden fable
#

U r currently checking if the list is there

#

U gotta check for each element in the list

crystal wind
#

Yeah, I was wondering how you would use a for loop in this case

#

Lemme try it out

maiden fable
#

?

patent lark
#

?

maiden fable
#

Ah, snow

#

Long time

patent lark
#

indeed, hello hunter.

maiden fable
#

Mhm

crystal wind
maiden fable
#

Weird

#

Wait

#

I did the opposite OMG

crystal wind
#

response.amongus[res] perhaps?

patent lark
#

🪑

crystal wind
#

o wait no you don't need to since it's a for

maiden fable
#

any(word for word in response.amongus if word in message.content)

#

This is the correct one

visual island
#

hi

patent lark
#

lol you was iterating through the wrong thing 😭

maiden fable
#

ofc list comprehension

crystal wind
#

thank you she doesn't tolerate this anymore

maiden fable
maiden fable
#

Also don't make your variables like response.amongus

crystal wind
#

it's because it's stored in another py file

maiden fable
#

Ah

maiden fable
crystal wind
#

all my responses are in a second file so it doesn't like yk, get overwhelmed

patent lark
maiden fable
#

Ah okay. I thought they were in the same file, my bad

crystal wind
#

Also @maiden fable last question

#

What if I wanted to add an “and” condition for an additional specific word?

#

Would that be

if any(word for word in response.amongus if word in message.content) and “specificword” in message.content:

maiden fable
#

Sure

crystal wind
#

Oki thanks a lot!

maiden fable
#

(:

crystal wind
#

Let me know if someone is familiar with FFMPEG (not youtube related at all).

maiden fable
crystal wind
#

okok

crystal wind
#

One of my friends suggested me to silence the FFMPEG warnings through the console, although that didn’t work well.

#

Should I send you the code? It’s not really anything though.

#

@maiden fable forgot to ping xd

maiden fable
#

Well, FFMPEG is against ToS anyways cz it gets the music from YT, but for playing from a local audio file u can do that directly. No need for any third party software

crystal wind
#

Wait really? There’s a better way without FFMPEG?

maiden fable
#

It's in built haha

crystal wind
#

People told me I had to use FFMPEG to play things like sound

#

Well I did that

maiden fable
#

Nah it's for the time when u have to get music from YT

crystal wind
#

What do you use then?

maiden fable
#

I don't, for now. Waiting for voice receive, then gonna implement that thing in my bot

crystal wind
#

I never knew there was a better way to play local files, I might need to check for more documentation on this.

maiden fable
#

Lemme tell you how to do so

crystal wind
#

According to this guy, there wasn’t really documentation on it without FFMPEG.

visual island
#

!d discord.PCMAudio.stream

unkempt canyonBOT
maiden fable
#

I have made my bot play audio clips without ffmpeg

visual island
#

you can put the file bytes to PCMAudio constructor

maiden fable
#

Yea, that

crystal wind
#

Works with .wav?

visual island
maiden fable
#
with open("file", "rb") as f:
    # pass in f to the constructor
#

Hehehehe

#

Wait

#

What if vc is None?

crystal wind
#

and you too hunter :D

maiden fable
#

👍

crystal wind
#

I’ll try this tomorrow though cause it’s late xd

maiden fable
#

Is fine haha

waxen granite
#

how do i fetch_message from ctx.guild?

maiden fable
#

U need the TextChannel ID

waxen granite
#

using the msg id i get the channel then through channel get the guild?

maiden fable
#

U can't...

slate swan
#

why would you get a guild from a channel

maiden fable
#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
maiden fable
#

It's a text channel method

waxen granite
#

hm

#

and what should i do if i want to use the message url ?

maiden fable
#

U can use regex or something to get the message ID

#

Try printing VC

visual island
maiden fable
#

Told ya

#

Sorry, but idk

maiden fable
#

?

visual island
waxen granite
#

can i use this link itself to fetch the message and delete it

#

?

visual island
#

oh

#

no

maiden fable
#

?

waxen granite
#

so i gotta ftech the channel with id and then msg with its id

heavy radish
maiden fable
waxen granite
#
    async def deletemessage(self, ctx, ch: discord.TextChannel, message:discord.Message):
        ch = self.bot.get_channel(ch.id)
        msg = ch.fetch_message(message.id)
        await msg.delete()
        await ctx.send("deleted")``` like this then?
maiden fable
visual island
#

but you can await get_channel(343944376055103488).fetch_message(894085358772453406)

heavy radish
#

I'm still lost...

waxen granite
#

i just wanted to use the msg id

#

lazy xd

#

but guess its not possible

visual island
maiden fable
heavy radish
#

How do I make it so when I type the name of the role it pings it?

#
@bot.command()
async def g(ctx, member: discord.Member, role: discord.Role, *, arg):
  channel = bot.get_channel(886837547328761868)
  await channel.send(f"{role} \n **__Requirement:__** {arg} **__Host:__** <@{member}> \n \n **__Helpful Staff:__** {ctx.author.mention}")
  await ctx.send(f"Message was successfully sent to {channel}!!")
```I gave up on the other one...
maiden fable
#

!d discord.utils.find

unkempt canyonBOT
#

discord.utils.find(predicate, seq)```
A helper to return the first element found in the sequence that meets the predicate. For example:

```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
```  would find the first [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") whose name is ‘Mighty’ and return it. If an entry is not found, then `None` is returned.

This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.9)") due to the fact it stops the moment it finds a valid entry.
steel trench
waxen granite
#

'coroutine' object has no attribute 'delete' error

visual island
maiden fable
heavy radish
#

so without doing !g @help I do !g help

visual island
maiden fable
#

I ain't the one who can judge u

waxen granite
steel trench
visual island
#

btw

#

how to make this neater tho?

maiden fable
#

Just use flake8

#

It's gonna make that neater

#

Or black

visual island
#

b-but, i want to neat it myself :c

steel trench
#

Like so:
member.top_role.mention

visual island
#

oh

#

you're giving example

steel trench
#

Huh

visual island
maiden fable
waxen granite
maiden fable
visual island
visual island
waxen granite
#

hm

maiden fable
#

Then should have raised an error

waxen granite
#

ye something was wrog i guess

maiden fable
#

If it was wrong

#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
heavy radish
visual island
#

@waxen granite it raises any error or smth?

heavy radish
#

currently once works if I do tt2-19. If I do TT2-19 it doesnt work

waxen granite
lusty swallow
waxen granite
#

i did

steel trench
#

I’ve never tried

heavy radish
#

Oh

waxen granite
#

ok it still doesnt work for that msg

visual island
steel trench
maiden fable
waxen granite
#
    async def deletemessage(self, ctx, ch: discord.TextChannel, message:discord.Message):
        ch = self.bot.get_channel(ch.id)
        msg = await ch.fetch_message(message.id)
        await msg.delete()
        await ctx.send("deleted")```
heavy radish
#

Ok

visual island
maiden fable
#

And what u passing into those params?

lusty swallow
heavy radish
#

Where do I add this?

lusty swallow
#

aren't you already giving it a channel?

visual island
#

true

waxen granite
#
    @commands.command(help = "Delete a message.\n*PERM_NEEDED = MANAGE_MESSAGES*", aliases = ["delmsg", "delm"])
    @commands.check_any(commands.is_owner(), commands.has_permissions(manage_messages = True))
    async def deletemessage(self, ctx, ch: discord.TextChannel, message:discord.Message):
        ch = self.bot.get_channel(ch.id)
        msg = await ch.fetch_message(message.id)
        await msg.delete()
        await ctx.send("deleted")``` this is the complete code
visual island
maiden fable
#

Also, if the author already has manage messages perm, why make a command out of it...?

lusty swallow
maiden fable
#

.....?

lusty swallow
visual island
#

message.delete() when?

lusty swallow
#

aight cool

waxen granite
lusty swallow
waxen granite
lusty swallow
#

wait really? if there invoker already have a manage_messages perms, is there any reason to use the command? @waxen granite

reef shell
#

is your bot a public bot?

waxen granite
waxen granite
reef shell
#

Then why would you need such things

waxen granite
#

not everything has to have a meaning

reef shell
#

....

#

what you are trying to do is definitely considered a privacy breach

slate swan
waxen granite
#

maybe but its my bot.

reef shell
#

MaYbE

waxen granite
#

they agree to whatever my bot offers when they invite it

#

and how this code breach their privacy?

waxen granite
reef shell
#

So you are gaining delete messages permission in a server without the server's consent.

#

Does it seem okay to you?

waxen granite
#

depends on the situation

reef shell
#

huh?

waxen granite
#

as for mine, i did this for a specific server whose owner asked me to handle my bot but he cant give certain perms since i aint an admin

#

and he cant give me the perms for certain reasons

#

it will be a breach of privacy when i go on doing stuff randomly

#

when i abuse the commands

reef shell
#

ok

sly hamlet
#

Hello I'm in the process of making this command I want it to be able to post random photos like it is right now but when that happens I get the same photo in a row a lot of times is there a way to stop this from happening py @commands.command(pass_context=True) async def halloween2(self, ctx): with open("json/halloween.json", "r") as file: json_dict = eval(file.read()) answer = random.choice(json_dict['Things']) author = ctx.message.author em = discord.Embed(title="", description="", color=0x050505) em.set_image(url=(answer)) em.set_footer(text=f"Echo discord bot") await ctx.send(embed=em)

outer basalt
#

Anyone familiar with subclassed drop down/view ?

slate swan
#

Can I put the whole bot program inside a def functions

For example (ignore mistakes) ```py
def login(tok):
import discord

client = discord.Client()

@client.event
async def on_ready():
    print(f"Connected to {client.name}")
client.run(tok)```

And then run multiple bot by calling the function?

with open('tokens.txt', 'r') as f:
    for line in f:
        token = line.rstrip()

await login(token)```


Can I do this?
gloomy coral
#

Hellooo

#
import discord
import asyncio
import csv
from discord.ext import commands,tasks
from datetime import datetime
import pytz

class Vote(commands.Cog):
    def __init__(self, bot):
        self.bot = bot


    @commands.Cog.listener()
    async def on_ready(self):
        self.checkVoteTime.start()
        self.member_update.start()

    @tasks.loop(seconds=20)  # repeat after every 20 seconds
    async def checkVoteTime(self):
        #code tht works


    @tasks.loop(seconds=20)  # repeat after every 20 seconds
    async def member_update(self):
        dt_string = now.strftime("%-H")
        if int(dt_string) == 13:
            time = datetime.strftime(datetime.now(), "%H:%M:%S")
            time_IST = datetime.strftime(datetime.now(pytz.timezone('Asia/Kolkata')), "%H:%M:%S")
            data = [time, time_IST, len(self.bot.users)]
            with open("databases/members.csv", 'a+', newline='') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow(data)

            time = datetime.strftime(datetime.now(), "%H:%M:%S")
            time_IST = datetime.strftime(datetime.now(pytz.timezone('Asia/Kolkata')), "%H:%M:%S")
            data = [time, time_IST, len(self.bot.guilds)]
            with open("databases/servers.csv", 'a+', newline='') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow(data)

#

for some reason the csv isnt getting updated

#

why

gloomy coral
#

yea check onready

gloomy coral
slate swan
slate swan
#

Ooo

untold token
#

await will not work synchronous functions

slate swan
#

Any other idea? i want 4 of my bots to do same thing at same time and single python file

untold token
#

So you want to run 4 different bots through a single file?

gloomy coral
untold token
#

Like a global error handler?

slate swan
slate swan
untold token
#

Because when you call .run() method, it creates a main event loop, and anything below the first run statement will not run.

upbeat otter
#

:)

near sky
#

Uh

slate swan
#

Ok so I got in a bit of trouble lel_zz

For an upcoming event in my server, we have to set send_message permissions to ** in all the channels Note: We do not have to change permissions of the main roles, we have to change the permissions of the role for the channels only

And we have to leave a particular role (dyno muted) role as it is....

So the real problem is that I can't figure out what to do as I want to do it as fast as possible using my bot.... any idea??

near sky
#

I have a question

upbeat otter
near sky
#

line 87 has a syntax error

#

but it seems fine

upbeat otter
#

of line 84

vocal plover
#

*of line 84

near sky
#

what kind

untold token
upbeat otter
wraith osprey
near sky
#

hmm

untold token
#

But you need add good delays

wraith osprey
#

there's a missin bracket

untold token
#

You don't want your bot to get ratelimited

near sky
#

doesnt fix

upbeat otter
#

or just paste the code

#

:)

near sky
#

still

upbeat otter
upbeat otter
near sky
#

oh god

#

how do I not notice these things

slate swan
# upbeat otter Can you explain a little more :)

Ok so like

I have a server
I have many channels
I have many role
I have a bot

And every role has send_message permission to True

So what I want to do is **To set the permissions of every role (except dyno muted role) in every channel as send_message to ** **

Without editing the permissions of the main roles

I am afraid that I am unable to simplify it more that this Please help

near sky
#

thank you

upbeat otter
upbeat otter
#

or just edit the roles?

slate swan
#

Of all the roles

upbeat otter
#

send_messages=False

slate swan
#

But there are 30+ roles and many channels

#

Can you explain a bit..

upbeat otter
slate swan
upbeat otter
#

yesh

unkempt canyonBOT
slate swan
#

I never played with rolesCryingOof

upbeat otter
slate swan
#

Permission of roles in text channels

#

Wait lemme send ss

upbeat otter
#

thanku

#

You can disable the channels like this py await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False)

slate swan
upbeat otter
#

@slate swan why not change the permissions of the text channel straight away?

slate swan
#

Wdym?

upbeat otter
# slate swan Wdym?

Do you need all roles to stop sending messages or you need some roles to send messages?

slate swan
#

All the roles (except some roles) to reset their send_message value to **

#

Lemme send 1 more ss

upbeat otter
slate swan
upbeat otter
#

I used roles to create custom roles :) But idk how to set perms for specific channels

slate swan
sly hamlet
#
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 4 column 5 (char 57)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting ',' delimiter: line 4 column 5 (char 57)``` ```py
 "Things":[
    "https://i.imgur.com/ERByCYG.gif",
    "https://i.imgur.com/oE5LmW6.jpg",
    "https://i.imgur.com/ERByCYG.gif",
    "https://i.imgur.com/7osxm2r.jpg",
    "https://i.imgur.com/bXXNBaK.jpg"
]```
slate swan
slate swan
unkempt canyonBOT
#

property roles: List[discord.role.Role]```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of the guild’s roles in hierarchy order.

The first element of this list will be the lowest role in the hierarchy.
sly hamlet
# upbeat otter wheres the code :)
@commands.command()
    async def halloween2(self, ctx):
      with open("json/halloween.json", "r") as f:
        json_dict = json.load(f)
      answer = random.choice(json_dict['Things'])
      author = ctx.message.author
      em = discord.Embed(title="", description="", color=0x050505)
      em.set_image(url=(answer))
      em.set_footer(text=f"Echo discord bot")
      await ctx.send(embed=em)```
visual mesa
#

hey everyone, im sorry if this break the 5th rule [Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.], just moved from #python-discussion [#python-discussion message]

i have some issue with my script, which it would spit py Command raised an exception: TypeError: json() takes 1 positional argument but 2 were given at me, i've heard someone saying i should use tuple, and im not sure if i did so correctly, heres my script: [https://paste.pythondiscord.com/vejerimiqo.py], oh and ignore that i havent changed things for the private ip output

oh and some backstory again:
the script is cropped from my old mc server status checker, i made that script so that it would check my ip every 1 time (im planning to make a way so it compare the new and old ip before nmapping it), and then it would nmap one of my port, and then i would grab the status of status for my port , if its opened that it would get detected as a public ip, else it would detect is as a private ip

once again i appreciate any replies, and im sorry if this breaks any rule

Discord

Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.

upbeat otter
#

random.choice does not work on dictionaries ig :)

sly hamlet
upbeat otter
slate swan
#

Then, py for role in ctx.guild.roles: await ctx.channel.set_permissions(role, send_message=False)?

visual mesa
sly hamlet
#

If you look up it is the thing that says things minus the {} at the beginning and end

upbeat otter
slate swan
upbeat otter
sly hamlet
upbeat otter
#

because using roles you are defining every role

slate swan
slate swan
upbeat otter
sly hamlet
#

Exactly but it does not

slate swan
upbeat otter
slate swan
slate swan
slate swan
#

?

#

send_message=None?

#

i mean py send_messages = None will do it

#

Oooo

#

yes

#

Thx

sly hamlet
slate swan
#

Dhanyavaad

#

😂 i see

#

:)