#discord-bots
1 messages · Page 513 of 1
It should be discord.Guild but here it says discord.guild
I'm assuming you imported guild which you shouldn't do
is there an event like on_message_edit for embeds?
on_message_delete how get who delete the message?
okey discord.Guild.get_member(and whats the id now.. Nothing works here wtf)
discord.Guild is the class
You want the instance of the class
Do not run methods directly on discord.Guild
I don't think that's possible
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
It's not possible for the bot to view the audit logs. Discord doesn't allow that.
Yes it is
and what should i write here .. idk what you want sorry c; i want only to check if the player is banned
How?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
!d discord.Guild.audit_logs

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}')
```...
..
well, you’re asking about js inside a python server, i don’t know what you expect
https://i.hdskins.de/yozI3/TAqEWuqi83.png/raw i need here something to find out if the member i tag or member id is banned from the discord
use await bans() and iterate over the list to find out if the member you tagged is banned or not
there is no await bans xd
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")
This wouldn't work
why
!d discord.Guild.fetch_ban
await fetch_ban(user)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the [`BanEntry`](https://discordpy.readthedocs.io/en/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.
As guild.bans() returns a list of BanEntry objects
use that instead
some know why i have here problem?
Not discord.Member objects
users is not defined
you seem to lack python knowledge
u help me with that?
and basic at most
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
right, i am just supposed to define users for you
yeah
Fair enough, thank you for the correction.
What's a BanEntry object?
you’re using json files
ya
!d discord.BanEntry
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").
Basically just an object that holds user and reason
so you could do BanEntry.user to get the user, right?
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
you can call me this 1 line? ;D
Yes you would
andy
andy? you have an idea for this line?
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()
there is a way to check if the bot is mentioned without using on_message event?
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?
no
use wait_for and if statements to see what they reply with.
can u give an example of how that would go into the code?
Really sad
example pls?
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
!d discord.ext.commands.Bot.wait_for
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**...
go to the link, it has examples of how to use wait_for
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
use a database, add them in it after they use it, if they use it again check if that member is in the database, if they are then send something else if they are not then send what you are going to send
can you copy and paste the code? sending an image makes it harder to know whats wrong
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Yeah I figured something like that, I want it to remove the member from the database after a certain amount of time though
asyncio.sleep
I want it to work if the bot goes offline though
i cant think of anything else
huh?
yea use asyncio.sleep
Hasn't passed
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
I tried
@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
what database are you using?
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
sqlite3
I'm trying to send a message to the channel where the message was sent
I think that is more confusing now lol
I'm trying to respond to a message to the channel where that message was send
It requires the context which can be an user or the guild channel
you cant have two of "" in 1 .send
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
Cuz PyCharm throws warning if the line exceed a certain value and warnings triggers me D_D
Nope, is nextcord.py but is pretty the same, barely no differences
idk what kind of sql uses db.field
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:
btw field is a method that i write in the db.py file
it returns me the value that i'm looking for as a string and not a list or tuple
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?
what u mean for lines?
Im creating an eval command I would like to cut it off after a certain amount of lines of text
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
How would this help me cut the lines off at a certain point though?
Ever used slicing with lists?
lst = ["a", "b", "c", "d"]
print(lst[1:-1]
will print b, c
I've never used splicing with lists only with strings
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
Doesnt doing that only split a specific amount off the end?
?
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
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
I will try it out
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
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
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).
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?
Mhh check in the discord.py documentation if there is something to make the bot leave from the guild, but i don t think that exists something like that
I didn t understand
U wait now i understand
so basically it takes the argument ive given, being "t" and "m", and matches it with the user and role that best matches the arguements
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
@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.
Note that u have to use the startswith method
i think ill just pass on it 
!e
lst = ["test1", "test2", "test3", "test4", "test5"
print(test[2:-1] )
Uhm i ha e to check this better
You are forgetting a [
Lol
!e
lst = ["test1", "test2", "test3", "test4", "test5"]
print(test[2:-1])
@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
shit
I'm tired xD, sorry
!e
lst = ["test1", "test2", "test3", "test4", "test5"]
print(lst[2:-1])
@final iron :white_check_mark: Your eval job has completed with return code 0.
['test3', 'test4']
So see? It cuts the first two element and the last one
Yes I know
But lets say I add more elements onto it
!e
lst = ["test1", "test2", "test3", "test4", "test5", "test6"]
print(lst[2:-1])
@final iron :white_check_mark: Your eval job has completed with return code 0.
['test3', 'test4', 'test5']
Now it is showing test5
Change the -1 with 4
Basically what I am looking for is that no matter how many elements I add on
Remember, slicing is:
variable[start: end: step]
It will only ever send "test3" and "test4"
If you want it to change then use variables lol
Wdym
!e
lst = ["test1", "test2", "test3", "test4", "test5"]
a=2
b=4
print(test[a:b]
!e
lst = ["test1", "test2", "test3", "test4", "test5"]
a=2
b=4
print(test[a:b])
@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
!e
lst = ["test1", "test2", "test3", "test4", "test5"]
a=2
b=4
print(lst[a:b])
@final iron :white_check_mark: Your eval job has completed with return code 0.
['test3', 'test4']
I missed a parenthesies again lol
So change a to 1 and b to 5 it will print from 2 to 5
sure
The last one is step, it will step to your list
it will step the slicing process
!e
lst = ["test1", "test2", "test3", "test4", "test5"]
print(test[::2 )
I can t do this lol
!e
lst = ["test1", "test2", "test3", "test4", "test5"]
print(lst[::2])
Now i feel myself a bad programmer xD
!e
lst = ["test1", "test2", "test3", "test4", "test5"]
print(lst[::2])
@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']
you can
So, as u see, it steps through it
Why are you doing string slicing if you want to restrict newlines
Do you know you can count the newlines in a string
wait, what are you trying to do?
!e ```py
my_string = "a\nb\nc"
print(my_string.count("\n"))
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
2
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
Im trying to make it so my bot will only send a certain amount of lines while executing code
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]:
I still don't understand how im supposed to end up deleting all the lines after the limit
Just don t send them
firstly count the "\n" then see if it's > than the limit, then delete it
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?
Why u are sending the code to a file?
Can you paste the code?
I send the code to a file because I have no idea how to capture it in a variable
Is anyone familiar with FFMPEG with discord bots?
I can send the code but its really quit straight forward
I m not understanding at all what your command does lol
Are you familiar with the python bot eval command?
Nope
I wanted to do it myself
Ok, just make sure you make it safe
I would still hesitate to implement that, what if a friends or your account gets hacked, what if you accidentally run something etc etc
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?
--> 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│
→ 98│ with get(url, stream=True) as response:
99│ response.raise_for_status()
100│
101│ with open(dest, "wb") as f:
102│ for 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?
I'm not really worried about the hacking part because I think if their account gets hyjacked the person isn't going to go around in all of their servers and find my bot and then try to mess with my stuff. I also really doubt ill accidentally run something.
I also couldn't find the file if I tried. The bots github is like a literal maze
!source eval
Run Python code and get the results.
Thats the one
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
Can we use argparse in discord.py bot?
i have asked detailed q here, (plz let me know if i shall post all of it here, too big)
https://stackoverflow.com/questions/69421071/how-to-use-argparse-with-discord-py-bot
I am coding a discord.py bot (on repl.it right now). The requirement is to simply use the argparse on the discord command like it's used on a cli command.
The command is supposed to be like this:
!
Sure you can. But I prefer u use flags, as they are already implemented in discord.py
Code
thanks, can you please point me to a link for flags? thanks
thanks
i tried the exact first block of example code in this doc in repl.it and it gave error:
AttributeError: module 'discord.ext.commands' has no attribute 'FlagConverter'
anyone familiar with FFMPEG? not youtube related btw
i tried the exact first block of example code in this doc in repl.it and it gave error:
AttributeError: module 'discord.ext.commands' has no attribute 'FlagConverter'
Which version do u have?
Install dpy from master
i'm on repl.it
bruh
i think replit uses poetry not pip
?
discord 1.7.3
@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)```
Eh, idk then tbh. Never used that
@bot.event()
TypeError: event() missing 1 required positional argument: 'coro'```
ive used it once for testing my code but that was along time ago
Remove the brackets from event()
Remove the has_perms deco
Change time.sleep to asyncio.sleep
i dont need ()?
and remove the context arg
Why do you have the has_permissions decorator on an event?
Also why are you using concatenation with an f string
Yeah i need help with that
I don't know how to send a members @ in an embed
in the title
the string on the member isnt right the first one is " and the second one is '
ah
Just doing that wont mention them
yes you have to member.mention
I haven't tested it but ctx.author.mention wont work in the title
@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)```
ohh yeah
this is my code rn but it aint workin
remove ctx arg
on_member_join takes only member argument
also you might want to await asyncio.sleep(10)
messages is also not defined I think
Unless its built into discord.py
ill define it
Also don't use concatenation just use an f string
but bot doesnt have any attributes to delete_message
member: discord.Member will do correct
suggestions
You don't need it
For an on_member_join
member does the same as member: discord.Member in this situation
mhm
^
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....
What do you suggest I do for the delete message part
delete after kwarg
what message are you even trying to delete?
in py await bot.delete_message(messages)
What are you trying to delete?
the welcome message?
then await message.delete() define message to the message you sent
use the delete_after kwarg and set it to an int on the line u sent the message
or that
yes
Help?
May need help on that any doc that can help me with that since I have never actually done that before
.send("Hi!", delete_after=5)
huh
U can make use a dict
!d discord.abc.Messageable.send @boreal ravine
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**.
hmmm
It's an abstract class, hence abc
How?
@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
why is there view is there is this the master branch?
role_dict = {1: role-object, 2: role-object}
Yea
Ahh
docs say flagconverter is new in v 2, discord py is at a.1.7.x ?
await channel.send(embed=welcomeembed, delete_after=10)
use 2.0 version ig
do i change the role-object to the id
Install from master... Danny has seized development
Nope... guild.get_role
ok thanks
@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
You probably don’t have member intents enabled
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
!d discord.Intents
Lol
role_dict = {1: guild.get_role(id), 2: guild.get_role(id)}
No lol
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
oop
pip install -U git+https://github.com/Rapptz/discord.py
Run this, ezzz
i am on repl.it, they have 1.7 only
ye ig
Ayy @boreal ravine cheers it works great but is there a way to make it more asthetic
maybe its the , in your welcomeembed.set_thumbnail()
What do I do?
mess around with embeds
Because the message is so small
its fixed
!e
print("works lol",)
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
works lol
But everything works good even the delete after
ok
role_dict.append({1: guild.get_role(id)})
I just need to make it bigger tbh
Do I need to import anything
U need to define guild
Ye
What can I do to make the embed message bigger
Add more text
great idea loll
authors, footers, thumbnails
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)
!d discord.Embed
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 osprey intents?
i need intents?
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
What's the thingy that shows the @ and not like Flashy#6969
It will only take member
its like ctx.author something
oh
member.mention
.mention?
yes mention
how do i import all intents?
You cannot mention someone in a title btw
Ik
How would I make a text that sends there @ only above the embed
Just the @ nothing else
perhaps using ctx would work
bot=commands.Bot(command_prefix="owo", intents=discord.Intents.all())
``` and enable them at https://discord.com/developers/applications
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Like separate from the embed?
await channel.send(f”{member.mention}”, embed=embed)
Yes
hm
anyone mind joining a server to test it for me u can leave after
make the dict first?
If I'm allowed to ask that question that is.
u cant append something to a dict before it was made i think?
sure
Alright I'll dm you.
use an alt account
That's what Hunter said
What should I do then?
to lazy tbh
Imagine not having 5 ALTs
wait my wifi is acting up
np
i got a error now
errors? @flint forum
await channel.send(f"{member.mention}",embed = embed)
NameError: name 'embed' is not defined
Should I just add it to welcomeembed
bruh use ur embed var
What did you name your embed?
add a member param next to on member join
in the ()'s
alr try rejoinin
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)
but it's alr there
hm
Also error handlers
yes
Is this right?
why'd it send too
yay it works :D
two
multiple instances
ig idk
Btw you don't have to name the args int and arg. They can be named whatever you want
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!
channel is a variable to send to certain channels tho
and its an event
so it wont be invoked
Wasn't talking about him
o
Actually yeah he defined channel
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)
So there is a point
hm
nope its not that the bot is running 2 instances
token isnt comprimised
mulitple ctx.invoke nope
@flint forum
is ur bot on another site or something?
@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
the code/token*
look at what i said
okay
Use an f string for the title
huh
bru
I did
oh yeah
but the other wouldn't work eh
great
wdym?
You used concatenation and a f string. Just use a f string
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}")
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
Imagine using f strings, .format and concatenation in a command tho 😂
add member.mention
my problem with py is where to put stuff that i never used before
Theres literally no point of using concatenation in this situation. Hes already using an f string
yeah
Im not the best versed in dicts
await channel.send(member.mention, the embed, delete after kwarg)
Hm
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
Can you send the full code?
Just makes it easier for me to read
Okay
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
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
It says indent error
Literally an indentation error
its obvious
Yea just saw srry
So you sent the error here before even reading it?
Actually right now I was on android so there doesn't seem any indentation error
Wha
Because its 7:30 and I cant access my pc rn
Yeah I would really suggest against programming on phone
There are words there that says indent error I think
Here’s the code @final iron
imagine if glitch.com supported discord.py
i am using the code for flagconverter but it does nothing with the two commands that i shared after it, please advice / hint
What is the command supposed to do
Do you need the flags?
yes i do, i will work on that part too once the command triggers
Try to uncomment 12th line and comment 11th
You need a prefix right
ok checking
I don’t think commands.command will work, try client.command
Helo
Now I am getting inconsistent use of tabs and spaces error but I haven't used tabs
ok checking
so um, is discord.py discontinued?
Oh

I’m not sure, the article was kinda like stopping but idk really

oh shoot
Oh ye but the article said but I’m still using it
and i though discord.py was made by discord themselves
Nope
Oh
lol I used to think that too from the very beginning that it was made by discord themselves
Help
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)```
you coding from a phone 
Did you add spaces accidentally
The reply=
I don't think sticking = with variables affect the program at all
nope, all libs are made by other people (I think) although I think some discord staff are contributors to some libs idk
Okay but maybe the problem could be because the “reply= “ when “reply = “ idk?

how i can fix this error?
Send code with error
https://hastebin.com/xakupilofa.py
I get error after write this command
Sorry no experience with cogs
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
for member in ctx.guild.members:
try:
print(member)
except:
print('a')
tf this is only printing one time
print(member.name)
hm
are there more members in the server?
@slate swan noob
yea like 5
lmao ik what it does idiot
it wont do that for my shit
@slate swan does it have intents
yup
if you made it a global command, it might take as much as an hour to show up
ohh okay ty
np
nope, just discord’s issue haha
guild id param
uhhh i think you send the request to a different url— check the documentation
oh yeah you’re using a library
Someone can help with this?
yeah okay ty
to show up, u mean register the command? or do you mean if i make any changes it would have to take 1hr+ to show up? meaning if i made the command the first time, i would have 1 wait 1 hour+, but if i make any changes i just need to rerun the bot; or whenever i make changes it will take 1hr+ to edit?
Registration:
Global: 1h (same goes for edits)
Server Specific: Instantly (same goes for edits)
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
how can i check if a message is an embed
!d discord.Message.embeds
A list of embeds the message has.
Check if it's not empty
Are you using cogs?
how would i do that
are you using a command or event
event
Which one
on_message
How do I show a users name in the title like Flashy#6969 (title of an embed)
on an fstring or
f string {member.name}
k thx
embed.set_thumbnail(url=ctx.discord.Guild.icon_url)
Why it's giving error?
Concerning about commands with on_message(message)
I was wondering if you could verify a list of keywords that contains in message.content.
Well u should instead do commands the Python way, haha
!d discord.ext.commands.Command
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.
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
Ah yes
!d discord.on_message
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.
Don't specify the channel....?
only specify the self_deaf kwarg, nothing else?
Ah
!d discord.Guild.change_voice_state
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.
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.
if any(res for res in message.content if res in response.amongus)
U r currently checking if the list is there
U gotta check for each element in the list
?
?
indeed, hello hunter.
Mhm
aah I'm not sure if it works
response.amongus[res] perhaps?
🪑
o wait no you don't need to since it's a for
any(word for word in response.amongus if word in message.content)
This is the correct one
hi
lol you was iterating through the wrong thing 😭
ofc list comprehension
thank you she doesn't tolerate this anymore
Don't blame me. Just woke up lmao
😂
Also don't make your variables like response.amongus
it's because it's stored in another py file
Ah
👋
all my responses are in a second file so it doesn't like yk, get overwhelmed
hello kylee
Ah okay. I thought they were in the same file, my bad
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:
Sure
Oki thanks a lot!
(:
Let me know if someone is familiar with FFMPEG (not youtube related at all).
What's up. I can try to help
okok
It’s from this.
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
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
Wait really? There’s a better way without FFMPEG?
It's in built haha
Nah it's for the time when u have to get music from YT
What do you use then?
I don't, for now. Waiting for voice receive, then gonna implement that thing in my bot
I never knew there was a better way to play local files, I might need to check for more documentation on this.
Lemme tell you how to do so
Basically the title. I installed ffmpeg and discord.py[audio] already. I just need to learn how it works. couldn't find any tutorial for local audio files. and I cant understand anything from
According to this guy, there wasn’t really documentation on it without FFMPEG.
!d discord.PCMAudio.stream
A file-like object that reads byte data representing raw PCM.
I have made my bot play audio clips without ffmpeg
you can put the file bytes to PCMAudio constructor
Yea, that
Works with .wav?
sure
with open("file", "rb") as f:
# pass in f to the constructor
Hehehehe
Wait
What if vc is None?
Thank thanks
and you too hunter :D
👍
I’ll try this tomorrow though cause it’s late xd
Is fine haha
U need the TextChannel ID
using the msg id i get the channel then through channel get the guild?
U can't...
why would you get a guild from a channel
!d discord.TextChannel.fetch_message
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.
It's a text channel method
bot._connection._get_message(ID).url?
Mostly gonna return None cz only a 1000 messages are cached (be default)
Told ya
Sorry, but idk
?
bot.max_messages = 1000000000
lets say i am trying to delete #discord-bots message this msg
can i use this link itself to fetch the message and delete it
?
?
so i gotta ftech the channel with id and then msg with its id
Wanna help me now?
Rip. Why tho. U don't want the RAM to be filled with only messages and nothing else, do u?
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?
Didn't I tell u before?
but you can await get_channel(343944376055103488).fetch_message(894085358772453406)
I'm still lost...
sure
uh, no..
mhm
Then dont do that
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...
!d discord.utils.find
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.
You want it to actually ping the people with the role?
'coroutine' object has no attribute 'delete' error
ye

Eh, it's your bot, your wish haha
so without doing !g @help I do !g help
await the fetch_message()
I ain't the one who can judge u
ah
Add .mention
b-but, i want to neat it myself :c
Like so:
member.top_role.mention
Huh

Well, then use flake8. It's a style cum type checker, which would show errors related to neatness as well as tell u about type errors
well the msg is there but it says cant find the msg, is this a cache error?
Nope. It fetches from the API
fetch_message() don't grab the message from cache
the channel or message id is wrong? maybe?
hm
Then should have raised an error
ye something was wrog i guess
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.
Works, can I make the role name case insensitive?
@waxen granite it raises any error or smth?
currently once works if I do tt2-19. If I do TT2-19 it doesnt work
discord.ext.commands.errors.MessageNotFound: Message "893534664222982164" not found.
hmm
did you give it the right channel?
i did
In all honesty I don’t know
I’ve never tried
Oh
ok it still doesnt work for that msg
can you show your code? *not the deletemessage function
Try another one
U can do .lower() with the role name
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")```
Ok
i mean, when you call that function
And what u passing into those params?
is there any reason for this ch = self.bot.get_channel(ch.id)?
Where do I add this?
aren't you already giving it a channel?
true
@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
how did you invoke the command?
Also, if the author already has manage messages perm, why make a command out of it...?
@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: int):
msg = await ch.fetch_message(message)
await msg.delete()
await ctx.send("deleted")
```Try this maybe?
author dont have
.....?
your checks says otherwise
wait..
message.delete() when?
worked ty
aight cool
i am the bot owner but i dont have the perm in the certain guild
yeah i misunderstood the checks nvm
it just checks if the bot has manage message lol
well it checck if the command invoker is owner or has perm manage_messages
wait really? if there invoker already have a manage_messages perms, is there any reason to use the command? @waxen granite
is your bot a public bot?
what if the cmd invoker dont have the perms?
yes
Then why would you need such things
i code as a hobby
not everything has to have a meaning
like me
maybe but its my bot.
MaYbE
they agree to whatever my bot offers when they invite it
and how this code breach their privacy?
😄
So you are gaining delete messages permission in a server without the server's consent.
Does it seem okay to you?
depends on the situation
huh?
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
ok
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)
Anyone familiar with subclassed drop down/view ?
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?
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
Are you starting the task?
yea check onready
checkvote works
Any errors?
I wish someone to be here for me as well
i think no, not sure
Ooo
You cannot
await will not work synchronous functions
Any other idea? i want 4 of my bots to do same thing at same time and single python file
So you want to run 4 different bots through a single file?
nope
you could try ```py
client.run(token1)
client.run(token2)
client.run(token3)
client.run(token4)
This will not work
:) what
i said but i just thought of it i dont know if it would work
Because when you call .run() method, it creates a main event loop, and anything below the first run statement will not run.
:)
Uh
Ok so I got in a bit of trouble 
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??
I have a question
Can you explain a little more :)
*of line 84
what kind
Well, if you have a lot of channels and roles, you need loop through
)
)
hmm
But you need add good delays
there's a missin bracket
You don't want your bot to get ratelimited
doesnt fix
Mine gets ratelimited without any loops etc :)
you havent closed the bracket where you use the length function
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
thank you
i see
its okay
so...You wont to disable send_messages permissions to some channels right?
or just edit the roles?
Yea without editing roles
Of all the roles
just change the channel permissions ig
send_messages=False
just loop through the channel ids, and overwrite the permissions to send_messages=False
guild = ctx.guild
for channels in guild.channels:
``` I got confused
yesh
Hey @visual mesa!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
how do I changed perms of every roles using this?
I never played with roles
You said you didnt want to change roles, but only text channels ;-;
thanku
You can disable the channels like this py await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False)
Will this do this??
Bot will list all the roles here and set their send_message value to false
ohh i see now
@slate swan why not change the permissions of the text channel straight away?
Wdym?
Do you need all roles to stop sending messages or you need some roles to send messages?
All the roles (except some roles) to reset their send_message value to **
Lemme send 1 more ss
I am clueless about how to do that :) search google or docs

I used roles to create custom roles :) But idk how to set perms for specific channels
await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False)``` will change perms for default role ( `@everyone` ) only
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"
]```
i wrote the same thing :)
I want to change perms for all the roles...any idea?
wheres the code :)
!d discord.Guild.roles ```py
for role in ctx.guild.roles:
change perms for role```
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.
@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)```
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
how does your json file look like?
random.choice does not work on dictionaries ig :)
Seems to always have worked for me
can u show me your json file :)
Then, py for role in ctx.guild.roles: await ctx.channel.set_permissions(role, send_message=False)?
oh and heres the version that run perfectly fine outside discordpy that i used in that script:
[https://paste.pythondiscord.com/ejusawixal.swift]
If you look up it is the thing that says things minus the {} at the beginning and end
why not use an array and only a json file?
@upbeat otter What do you think about this?
ask @slate swan it may work or may not
Because this was already built from 2 years ago when I was using it I have no interest in moving it all over I just need it to work again
because using roles you are defining every role
yes sure , but it will change all the perms to send_messages =False only , i.e. all other perms would be set to default
So it will not edit the main roles right?
oh i see, it should work according to me tho
Exactly but it does not
it will
It will unless your bot doesnt have permission to change their roles
No no my bot has admin perm
Also 1 thing....if what if I want to set the permission to \
None
?
send_message=None?
i mean py send_messages = None will do it
Oooo
yes
Thx
@upbeat otter this is the error I keep on getting

