#discord-bots
1 messages Β· Page 551 of 1
wym? is it not?
O-O
yeah and?
you said "his playlists sounds edgy" and he was asking "how did you know that"
i think you minunderstood me here. When kayle said "people stalking people's spotify now?", i replied with just his like i only stalked his SA and his SA only
What Playlist 
Off-topic channels
There are three off-topic channels:
β’ #ot0-psvmβs-eternal-disapproval
β’ #ot1-perplexing-regexing
β’ #ot2-never-nesterβs-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
snap back to the channel's topic
can someone tell me how i can make an afk command with sqlite3? ive tried making it on my own, but its glitchy af. maybe you can recommend some tutorials or smthng? if its in a different db, like postGRE, i'll convert it to sqlite i just need some reference
or can you link the repo of a bot with an afk command?
Well first of all, you should use an asynchronous library. Maybe aiosqlite, or asyncpg if you prefer PostgreSQL.
Now... What is an afk command?
now that i think about it, i think the reason it fucked up is cuz i didnt use the async version of sqlite lol
how can i update my discord.py version to 2.0 in replit?
AFK Command: If a person set his AFK to something like !afk Don't ping me, then if someone pings that person, the bot sends the message Don't ping me
u know to use git?
Same thing for every IDE pip install -U git+https://github.com/Rapptz/discord.py
how do i stop the bot from deleting the user's messages when banning?
!d discord.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
alright thanks
hey guys, I am working on a music bot, I'm currently using yt-dl to source the audio, is there a way to use Spotify or some other source with a better audio quality for the same?
don't tell me you used that youtubers video
nahh
I didn't refer yt for this project
I rarely refer yt for projects
sure you didn't
bruh
I made a music bot using ytdl but I've never seen any yt vid whatchu talking about 
well
theres been a lot of people asking for help about youtube_dl here
and I found the video they got the code from he didn't even explain what the code did
You can't
π
anyways
You could make a global var and change it in the command tho
I'm not asking for help with yt_dl
I only copied the example from the repo because I was too lazy to bother with configuring it π
The rest i improved π
@slate swan
bruh
only copied, too lazy
thats not how it works
the discord.py voice example? or which one
The commands and the logic I made myself
Disnake's voice
It is π
Tbh i only needed to copy the configurations π
@slate swan your russian?
No
hm
wow
what made you jump to that conclusion
^^
idk
bruh
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Like I even have a link in my bio which has some info about me πβ
not sure if you can lol, just do the counting in the task itself then stop it
same thing goes for spotify
The long awaited !ytdl
I'm not asking for help with yt_dl
They asked for Spotify
It's the same
You don't ask for help, but you use it. And using it makes us impossible to help you :p
good luck downloading stuff from spotify lol
It's not the same
or some other source with a better audio quality for the same?
Ytdl != Spotify
I meant the ToS
You realize it's the terms of service?
π
Spotify has the same thing in their ToS?
Probably yeah
Why would they accept something like that kekw
"Probably"
"probably"
π¦ π¦
Spotify doesnβt support streaming audio source like tgat
and so many other sources out there
i mean its kinda common sense, if spotify doesnt do the same then they're losing money too
I was just asking for your opinion
copying, reproducing, redistributing, "ripping," recording, transferring, performing, framing, linking to or displaying to the public, broadcasting, or making available to the public, or any other use which is not expressly permitted under the Agreements or applicable law, or which otherwise infringes intellectual property rights;
https://www.spotify.com/us/legal/user-guidelines/?_ga=2.74992274.1463521725.1634807135-1556900206.1632746656
and if someone has worked on a similar project
who pinged
Oh didn't know that
The music bot's do take the title and author name from spotify and search it up on youtube to get the song, eventually leading to use ytdl
It's just so obvious that streaming platforms don't like their service to be streamed
Not rocket science
that's what I found all over the internet
but I was just wondering if there's some other source available out there
Specifically when they make profit from their service
i cant find it
idk how and this is not the right place to ask for this
fine
They won't allow even if you offer free services tho, because youtube/spotify can't get ad revenue on those streams
lol, they will develop their own bot and put audio ad in
discord will be releasing a new feature regarding this, It's called youtube together which will allow you to watch yt videos in vc
xDD
mhm
And that includes ad
not looking forward to it
ad-blocker
u cant use ad blocker on spotify
yes......
yes
I was talking about yt
oh
nvm
cool

Off-topic channels
There are three off-topic channels:
β’ #ot0-psvmβs-eternal-disapproval
β’ #ot1-perplexing-regexing
β’ #ot2-never-nesterβs-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
quite cool tho
!d discord.Message.edit
await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other peopleβs messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
Message.edit
await message.channel.send("https://images-ext-2.discordapp.net/external/r_HR-WHA2AzKT3y9NwUWCCiWCpKH440-5B_0_sxrcm4/https/i.imgur.com/w5vm9l8.mp4")
time.sleep(5)
async def on_message(message):
if 'https://imgur.com/qJyjIIN' in message.content:
await message.edit(message,"https://imgur.com/qJyjIIN")```like this
lmao
try it and see
uh
But no, you dont pass the message, only the content you want to edit
no work, just the first part444
Does anyone know how to make slash commands in py-cord? I tried to use the code from the example but it didn't work
Well you dont call the function you define
ok
if message.content.startswith("g!wish"):
await message.channel.send("test")
async def on_message(message):
if 'test' in message.content:
await edit(message, "testtest")
help
Why u defining another function...
async def on_message(message):
try it
ok
work the first part only
only gib me test
not testtest
if message.content.startswith("g!wish"):
await message.channel.send("test")
if 'test' in message.content:
await edit(message, "testtest")```
uh
also, by the way
you're checking if "test" is in the original message's content
not the message you sent right above that
... the message.content
well no, i'm not going to spoonfeed you, but i'm here to help
that's not the correct syntax
can u help me with the syntax
read this again
oh wait
apologies, i made a slight mistake
np
you need to put the new message as content
await message.edit(content="new content")
because it's how the library works
oh, ok
https://stackoverflow.com/questions/55711572/how-to-edit-a-message-in-discord-py
shouldnt watch this page
yeah, look at the docs instead
lmao,still cant
hehe
if message.content.startswith("g!wish"):
await message.channel.send("test")
if 'test' in message.content:
await message.edit(content="testtest")```
lmao
You can only edit messages you sent (you being the bot....)
I'll ask you a simple question, can you edit your friends' messages?
Your also still only checking the original message. as you were told before but π€·ββοΈ
We dumb dumb
Are you using message events to make commands?
Yes
im editing my own msg now
if you want to edit the message you sent right above that, assign it to a variable then edit it
So you can edit everyones messages? Shesh
Because it's sent by you 
heh
Yea, but your not your bot
uh,lmao
i know, the bot is editing its own msg
And that's the only messages your bot can edit
yeh
im coding it to edit that
if message.content.startswith("g!wish"):
await message.channel.send("test")
if 'test' in message.content:
await message.edit(content="testtest")
like it send test and edit it to test test
lmao, what should i do
what
yeh, i try
no error but no fix
ok
but where, send me the link
i like watching tuto but not reading
uh, ok ty
oh
i saw 1ty
why is the command not getting deleted in one server
@bot.command()
async def say(ctx, *, arg):
await ctx.send(arg)
await ctx.message.delete()
in my test server the bot deletes the trigger
but in only one server it doesnt get deleted
does the bot have manage_messages perm in that server?
it has admin
Well, if it works in one but not in the other then it's a problem with the other sever's bit permissions
No, what you should try is fixing the problem in that other server
Hi
hey maid
!d discord.Message.edit didn't i already give u this earlier
await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
uh
yk if you dont understand just ask Β―_(γ)_/Β―
lmao, dont understand
if message.content.startswith("g!wish"):
await message.channel.send("test")
if 'test' in message.content:
await message.edit(content="testtest")
it just show test not testtest with edited
set a variable where you sent the message
uh how, can u teach me
then edit it using await variable.edit("testest")
what?
i know how to make a variable tho but
if message.content.startswith("g!wish"):
bruh = await message.channel.send("test")
if 'test' in message.content:
await message.edit(content="testtest")
bruh.edit()
save what
at message.edit()
ih
ok
i know how to make a variable tho but
if message.content.startswith("g!wish"):
bruh = await message.channel.send("test")
if 'test' in message.content:
await bruh.edit(content="testtest")
like this
if message.content.startswith("g!wish"):
bruh = await message.channel.send("test")
await bruh.edit(content="testtest")
what do i wrong
try it and see
^
You can also send us errors..
Fix your indentation so its all in line
???
ok
This is fairly basic python
@devout quest pls learn more python
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
If you don't understand indentation you need to learn more python. This is the basis of the entire language
Imagine having to learn someting. Sorry
yeh
L
await needs to be within an async function
ok
But go learn some more python first, otherwise I won't be helping for my own sake
basic python
<@&831776746206265384> ^
!mute 789832854258450434 24h Refrain from spamming.
:incoming_envelope: :ok_hand: applied mute to @devout quest until <t:1634976339:f> (23 hours and 59 minutes).
@arctic python ^
Dm @novel apex if you want to talk about infractions
!ban 644523101257728020 Ban evasion, alt of 789832854258450434
:incoming_envelope: :ok_hand: applied ban to @dense granite permanently.
!ban 789832854258450434 Ban evasion, alt of 644523101257728020
:incoming_envelope: :ok_hand: applied ban to @devout quest permanently.
Isn't it "mute evasion" 
You get the idea
Well, yeah
"bruhmao" "hu tao"
Ham
async def on_member_join(member):
await bot.get_channel(891878891889766414).send(f"welcome **{member.mention}!**")```
how would i be able to turn this welcome message into an embed?
just send it like a normal embed
embed = discord.Embed(description=f"Welcome **{member.mention}**")
^
where would i put it though srry been a while since i used embeds
@bot.event
async def on_member_join(member):
await
embed = discord.Embed(description=f"Welcome **{member.mention}**") bot.get_channel(891878891889766414).send(embed=embed)```
@slate swan
no spoonfeeding
ty
If you wanna send an embed just await ctx.send(embed=embed) but be sure to define your embed beforehand
bruh
No problem
"where would i put it though srry been a while since i used embeds"
What he said
!d discord.TextChannel.send
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**.
two greens fighting huh
π©
Yea sure
How do I import discord.py?
did you install it yet?
yes
oh
import discord
At the top of your code
no no that's not what I meant
Then?
Like, how can I import discord.py and see the files in it
It's on GitHub
github
PyCharm wont let me go through discord.py
Oh can u guys send me the link in github?
I'd recommend using py-cord anyways it's mantained at least
Yea hold on
He was faster
For Python?
literally .py
how dumb question
so one more question and I'll proceed with my code, I wan't to make a fully functional and SAFE eval command, is there any tutorial for it?
Yeah
Python is a language, so is JS
Probably not but go find one maybe
could u send the docs to snekbox
jishaku is the easiest and widely used
hmm, what does it do tho, eval(arg) isn't enough?
snekbox requires actual effort since its containerized evaluation etc
@slate swan :white_check_mark: Your eval job has completed with return code 0.
hello
Run Python code and get the results.
You asked for safe lel
use jishaku tbh, likely enough for your needs if its only eval for your usage
async def post_eval(self, code: str) -> dict:
"""Send a POST request to the Snekbox API to evaluate code and return the results."""
url = URLs.snekbox_eval_api
data = {"input": code}
async with self.bot.http_session.post(url, json=data, raise_for_status=True) as resp:
return await resp.json()
``` this is the main part of the code
you just send a post result to snekbox and get the output back
the rest of the code manages revaluates, output formatting and stuff
So, how come there is a unsafe eval and a safe eval, I haven't understood that yet
well if you're using eval(code), you're running that code on your machine
that is equivalent to letting someone type some code on your computer and running it
so I could basically hack the owner of Python Bot if it wasn't safe?
it is hosted in some hosting service, so no
if the bot runs on the owner's computer then yes
daaang, so I have to make the command so only I can run it right
yeah, if you're planning on going the eval(code) way
(fwiw, we do go the eval(code) way for internal eval commands that only admins can use)
mhm okay i get it, so snekbox is another way of doing eval() right
Simple discord.py Eval Cog. GitHub Gist: instantly share code, notes, and snippets.
this is a safe one right?

!e x = input(">>> ")
@slate swan :x: Your eval job has completed with return code 1.
001 | >>> Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
why wont eval let me take inputs?
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Would have been fun if it was π
No need to use wait_for
I'm trying to build the eval code from scratch now but it doesn't work,
from discord.ext import commands
class Command(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(hidden=True)
@commands.is_owner()
async def eval(self, ctx, *, args):
await ctx.send(exec(args))
def setup(client):
client.add_cog(Command(client))
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
you can achieve that
sys.stdin = message in on_message event
Hmm
actually, you need to write it in a file
Good idea
or no idk
Wait, sys.stdin should be message.channel
never tried that
Since message is just.... a message?
it needs ByteIO or StringIO idk
a channel is just a channel
Which can receive text lol
Anyways who knows how to do that
that would make my sys.stdin to a string
Well your making it a message object atm
thinking of
sys.stdin.write(m.content)
io.UnsupportedOperation: not writable
```this
TypeError: write() argument must be str, not _io.StringIO
i provided a string before bruh
python's confusing
ohh
Then you can write to it
wait
But hey π€·ββοΈ
You gave it a string mwaahaha
StringIO is a useful way for mocking, or taking over stdin
https://docs.python.org/3/library/io.html#io.StringIO
It's just an in memory buffer
What doesnt do anything
@bot.event
async def on_message(m):
import sys
import io
sys.stdin = io.StringIO(m.content)
sys.stdin.write(m.content)
print(sys.stdin.getvalue())
```so apparently this works...
but what should I do with it...
Whatever you want
Issue is stdin is one stream, while each discord channel can in theory be its own
At which point, given sequential program execution theres no point
imo
it was hunter's dream ^^ yeah
yeah I love importing stuff in functions
normally i like
i do py import os print(os) if os: import os if __name__ == "__main__": import os def x(): ... x() import typing from typing import * main() from tkinter import * if tk.os: from tkinter import * from tkinter import tk import discord import discord.ext from discord import ext
this my favourite
i also just stick from tkinter import * in random places
why not, right?
my main.py looks like this
why not just import it once
why do you need it twice
omg
async def info(self, ctx, arg: typing.Optional[typing.Union[discord.User, str]] = None):
embed = discord.Embed()
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.set_footer(text=f"Information requested by: {ctx.author} ({ctx.author.id})",
icon_url=ctx.author.avatar_url)
if arg == discord.User:
embed.add_field(name=f"{arg.name}", value=f"empty")
embed.colour = 0x6495ED
return await ctx.send(embed=embed)
elif not arg:
embed.add_field(name=f"{ctx.author.name}", value=f"empty")
embed.colour = 0x6495ED
return await ctx.send(embed=embed)
elif arg == "server" or arg == "guild":
embed.add_field(name=f"{ctx.guild.name}", value=f"empty")
embed.colour = 0x6495ED
return await ctx.send(embed=embed)
else:
embed.add_field(name=f"a", value=f"a")
embed.colour = 0xFF6347
return await ctx.send(embed=embed)
How come when I mention a user like -info @slate swan it runs the else statement and not the first if statement?
@commands.command()
@commands.has_role("Admin")
async def add(self, ctx, member:discord.Member, role:discord.Role):
if member is None:
task_embed = discord.Embed(title=":white_check_mark: Success!", description=f"Successfully added {role.name} to {ctx.author}", timestamp=ctx.message.created_at)
await ctx.author.add_roles(role)
await ctx.send(embed=task_embed)
Why when I live empty the member arg, i get the error:
raise MemberNotFound(argument)
discord.ext.commands.errors.MemberNotFound: Member "<@&896699994483064952>" not found.
Why do you put an Union
Just type hint it to a discord user
Then you can do -info @mention/id/name
because if someone does -info server which is a str, it's going to post info about the guild the command ran in
arg == discord.User ?
you must use type or isinstance to check if the arg is an discord.User
arg == discord.User is like doing py 'apple' == str
oh, okay how can I use type or isinstance in this case?
!d isinstance
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
so if isinstance(arg, discord.User)
sure
u sure that will work tho because it doesn't make sense to me
Try it and see
isinstance will look at arg and return true if its of type discord.User
What's the unstable API reference called again?
oh ok ty
master branch?
I thought it was called master. Yes thank you.
What version you using
You should be setting icon_url iirc
the latest one
π
2.0?
idk
in the docs it says set_image(*, url)
url is a keyword argument
try printing discord.__version.__
you don't need *
Therefore url=...
yes
but author is a member?
*, .. denotes a keyword argument, they can only be set using there name
yes
author is a discord.Member object and .created_at() is a datetime.datetime object
Also * in a function with no parameters behind it doesn't make sense, nor will it work
@valid perch isinstance wont work btw
oh ok thanks
Whys that?
What for?
if isinstance(arg, discord.User):
embed.add_field(name=f"{arg.name}", value=f"empty")
embed.colour = 0x6495ED
return await ctx.send(embed=embed)
instead of returning this, it returns the else statement
Whats arg supposed to be
arg: typing.Optional[typing.Union[discord.User, str]] = None
Thats a typehint, besides it can be optional
print(arg, type(arg)) for me
I'd like to see why isinstance doesnt work : )
Misa#2635 <class 'discord.user.ClientUser'>
is that a bot
Theres your issue then, its not User so isinstance won't return true
ya
How about making a command group 
oh can any1 of u guys join my server? i have to try it on a user then
Try it on yourself
The same way you'd try it on us?
but it will return my info no matter what
So why would us joining matter
Just do the command with yourself as argument
oh nvm it worked on myself
You can see if it works
How would I ignore this error so it doesnt appear in console?
TypeError: 'NoneType' object is not subscriptable This is turning up because the value isnt present in the databse
Check if iits none before you try use it and return
Or in your on_error event check if the error is an instace of TypeError and just pass it
@commands.Cog.listener()
async def on_message(self,message):
if message.author.bot:
return
for x in message.mentions:
print(f'{x.id} has been mentioned')
uid = await self.coll.find_one({"user_id": str(x.id)}) #getting the user ID if in db then getting reaction
reaction1 = uid["reaction"]
await message.add_reaction(reaction1)
This is my code would something like if uid == None: return work?
Yes
if not uid:
return
I dont want to do that since it would ignore type error in other commands also
Oh okay thanks
Maybe bc of ctx.author.created_at()
So when I use inline=True on my embeds, its always 3 fields next to each other but i want 2, otherwise everything is compact
how do I do that
dont think thats possible

you can use empty field name and value for the third field
and let the third field be 4th one
hmm okay, well how do I shorten the created_at and the joined_at date
strftime function
strftime function?
!strftme
!strftime
well , you can format datetime's data using strftime
example code pls?
!d datetime.date.strftime
date.strftime(format)```
Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
yes but could u give a example using either created_at or joined_at
!e py import datetime print(datetime.datetime.now().strftime("%#d %B %Y"))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
22 October 2021
^
how can i turn the month into number?
replace B with m
https://devhints.io/strftime check out this for more
ok ty
How do I display the date a member's account was created in an embed?
<user>.created_at
Embed.timestamp = member.created_at
python discord has one -> @unkempt canyon
why at the timestamp?
they want it in embed
Ok thx
embed.add_field(name="Created At:", value=f"{member.created_at}")```
is probably what they wanted
let them decide what they want to do with it. we've already given sufficient answers
correct
!d discord.Member.created_at is that they want , where to use it is thier decision
Β―_(γ)_/Β―
a large discussion on such a small topic...?
π« exactly
Where in the docs can I find how to set a activity for my client?
I couldn't find it
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the clientβs presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter.
!d discord.Client.activity
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
The activity being used upon logging in.
!d discord.Client.status
property status```
[`Status`](https://discordpy.readthedocs.io/en/master/api.html#discord.Status "discord.Status"): The status being used upon logging on to Discord.
Thanks
but it doesn't work
from discord.ext import commands
class Event(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print(f"Started client as: {self.client.user}")
self.client.change_presence(activity="-help")
def setup(client):
client.add_cog(Event(client))
it returns a coroutine
wdym
You can set sys.stdin to your own stdin 
Mhm
It's a coroutine, you need to await it
And you shouldn't change the presence in the on_ready event, not good
oh ok ty
why?
You can just set an activity kwarg to your bot constructor
bot constructor?
Yes
When initializing commands.Bot
I do it everywhere?
When initializing commands.Bot
You only initialize it once....
idk what initialize mean
foo = Foo()
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/entrance.py", line 12, in on_message
mod_role = message.guild.get_role(886053029760106516)
AttributeError: 'NoneType' object has no attribute 'get_role'
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/entrance.py", line 17, in on_message
if mod_role in message.author.roles:
AttributeError: 'User' object has no attribute 'roles'
```got this error, code: ```py
@commands.Cog.listener()
async def on_message(self, message):
mod_role = message.guild.get_role(886053029760106516)
if message.channel.id == 890543918964432906:
if message.author.id == self.bot.user.id:
return
elif message.content not in ('des v', 'des ver', 'des agree'):
if mod_role in message.author.roles:
return
else:
return
```not using replit btw, its some sort of host just cant open vsc rn
how come i cant `get_role`? the role id exists
The message was sent in a dm

yed I did but idk what the terms are called because i learned it in swedish from school
i only know the smiple/basic python
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
What's the difference between discord.Member.activites and discord.Member.activity
I didn't understand it
one is plural the other is singular
omg no like, what is the difference of what they return
hey i broke my bot
;-;
i added the ping user command so that whenever someone pings the bot the bot will give the prefix back
but now any other command dont work
async def on_message(message):
mention = f'<@!{bot.user.id}>'
if mention in message.content:
await message.channel.send("My prefix is g \n Ya can type g help for more info")```
this is the code
can anyone help?
who knows??! maybe it's called activities because it returns many activities and the other is called activity because it only returns a single one??!!
I'm trying to do cogs but I am getting errors
for filename in os.listdir('/cogs/economy'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
FileNotFoundError: [WinError 3] The system cannot find the path specified: '/cogs/economy'
hint is in the fucking error
well yeah ik that but i have no clue on how to fix it
try relative path
you might mean ./cogs
Ok
normally it helps if you specify a path that exists, but each to their own
for filename in os.listdir("cogs"):
if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}")
Now it thinks that cogs is file?
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.bal' could not be loaded.
file is not defined
?
send the full traceback
well obviously he has to change it to filename why tf are u a pain
But would that still work with other folders within the cogs folder
just means bal.py is broken
send the file
it works just fine for me
class BalCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=["bal"])
async def balance(self,ctx):
bal_em = discord.Embed(title = f"{self.ctx.name}'s Balance", description = f"You have a balance of",colour=0xFFA500)
await ctx.send(bal_em)
def setup(bot):
bot.add_cog(BalCog(bot))
send the traceback, maybe you missed imports and whatnot
from discord.ext import commands
Ok
Traceback (most recent call last):
File "c:\Users\leogr\OneDrive\Desktop\robojackle2\main.py", line 17, in <module>
bot.load_extension(f'cogs.{filename[:-3]}')
File "C:\Users\leogr\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 676, in load_extension
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.bal' could not be loaded.
Thats already there
you have to import commands
then send the whole code in your file
import discord
from discord.ext import commands
class BalCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=["bal"])
async def balance(self,ctx):
bal_em = discord.Embed(title = f"{self.ctx.name}'s Balance", description = f"You have a balance of",colour=0xFFA500)
await ctx.send(bal_em)
def setup(bot):
bot.add_cog(BalCog(bot))
hmm let me see your whole main file, remove the token tho
Ok
import discord
from discord.ext import commands
from discord import Intents
import json
import asyncio
import os
import pymongo
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
bot.remove_command("help")
for filename in os.listdir('./cogs/economy'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
@bot.event
async def on_ready():
print(bot.user.name + " is online.")
bot.run("token")
thats not the full traceback
oh actually
It is
its extension not found
hm
oh you're listing cogs.economy but loading cogs
you have to do cogs.economy.*
in load_extension
Oh ok
That worked
Thanks
@commands.command()
async def info(self, ctx, arg: typing.Optional[typing.Union[discord.User, discord.ClientUser, str]] = None):
if isinstance(arg, discord.User):
platform = ""
if arg.is_on_mobile():
platform = "Mobile"
why does arg.is_on_mobile() not work? i tried arg.user.is_on_mobile() too
why are you typehinting as ClientUser
because I need it
why?
doesn't matter why in this issue
ClientUser is a class used by bot.user
yes
you cant use it like that
but im not checking for clientuser atm
how about you show us the error you get
its saying arg doesn't have a method called is_on_mobile()
arg should return discord.User in this case
So how do I solve it?
is_on_mobile is only for Member
typehint to discord.Member
yeah User cant magically turn into Member by doing User.member
so I can use two type hints in the isinstance()?
hm I see
one more question
discord.User will be if arg is a mention, would discord.Member also be a mention?
yes
ok nice thanks man
So in this case the solution is:
if isinstance(arg, discord.User) or isinstance(arg, discord.Member):
``` right?
but would both be True?
if isinstance(arg, (discord.User, discord.Member))
oh ok I didn't see u typed this, ty
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'User' object has no attribute 'member'
I dont get it
wtf did you do
you cant do User.member
async def info(self, ctx, arg: typing.Optional[typing.Union[discord.User, discord.Member, discord.ClientUser, str]] = None):
embed = discord.Embed()
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.set_footer(text=f"Information requested by: {ctx.author} ({ctx.author.id})",
icon_url=ctx.author.avatar_url)
if isinstance(arg, (discord.User, discord.Member)):
platform = ""
if arg.member.is_on_mobile():
platform = "Mobile"
elif not arg.member.is_on_mobile():
platform = "Computer"
embed.add_field(name="Name:", value=f"{arg.member}", inline=True)
embed.add_field(name="Nick:", value=f"{arg.member.nick}", inline=True)
embed.add_field(name="ID:", value=f"{arg.user.id}", inline=True)
embed.add_field(name="Created:", value=f"{arg.user.created_at.strftime('%Y-%m-%#d')}", inline=True)
embed.add_field(name="Joined:", value=f"{arg.member.joined_at.strftime('%Y-%m-%#d')}", inline=True)
embed.add_field(name="Activity:", value=f"{arg.member.activity}", inline=True)
embed.add_field(name="Status:", value=f"{arg.member.status}", inline=True)
embed.add_field(name="Platform", value=f"{platform}")
embed.add_field(name="Top Role:", value=f"{arg.member.top_role}", inline=True)
embed.add_field(name="Roles:", value=f"{arg.member.roles}", inline=True)
embed.add_field(name="Perms:", value=f"{arg.member.guild_permissions}", inline=True)
embed.add_field(name="worked", value="worked")
embed.set_thumbnail(url=arg.member.avatar_url)
embed.colour = 0x6495ED
return await ctx.send(embed=embed)
yes ik but we did discord.Member tho?
what?
async def info(self, ctx, arg: typing.Optional[typing.Union[discord.User, discord.Member, discord.ClientUser, str]] = None):
ok so what
if isinstance(arg, (discord.User, discord.Member)):
both dont have the member attr
but I need to access both of them?
?
both user and member
is_on_mobile is only for Member
yes
ok and you're checking for both User and Member
also, you should do Union[Member, User, ...]
why what's the difference if u dont mind explaining
User converter will never fail
because it calls the API if the user isn't cached
and if the one ur targeting is someone in the same guild it will convert it to User since the target is cached
well hopefully that makes sense
arg: typing.Optional[typing.Union[discord.User, discord.Member, discord.ClientUser, str]] = None
should be:
arg: typing.Optional[typing.Union[User, Member, ClientUser, str]] = None
is what you mean?
then what did you mean with?
read
yes I did but i'm not experienced enough to fix this issue, I understood it tho
that's why I'm asking for help
so making Member first in the Union requires experience?
its literally just moving it
So you meant, that I change from discord.User to discord.Member first?
yes
?
this
you still dont get the point
Member will fail if the user is not inside the guild
User will never fail
unless the api failed to get the user (if it isnt cached)
Ohhh okay thank you
btw my bot is fucked
i think I ran the bot twice
And I only have access to one terminal to close it, idk how to access the other one to close the second
maybe change the API key, which will stop the bot from running
Ok Thanks
How do i check if user got specific role added on on_member_update event?
compare before.roles with after.roles
!d discord.ClientUser.mentioned_in
mentioned_in(message)```
Checks if the user is mentioned in the specified message.
Is it a client.event?
its a method
Ok
When I try to get the channel ID, I get a statement like this.
Please tell me how to get just the id part of this statement.
that's the full channel
not the id of it
ctx.channel.id
is probably what you'd want
to like a user?
because then you just have to get the user
and do
await user.send("msg")
like if this is an on_message
which i think it is
you'd do, await message.author.send("msg")
If message.content.startswith(βbobβ):
await client.send_message(message.channel, {random.choice(resp)})
yeah
Ok
except no
So I write await user.send(βmsgβ)?
if message.content.lower().startswith("bob"):
await message.channel.send("msg")
It is
it would be like this
i'm pretty sure
Thanks
ofc
Hello i need help
How can i make like a slowmod if i make an command
like:
!beg
[command]
!beg
[Please wait 30m until the command]
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
I have a bot I added to a server, but it doesnt respond to the commands i give it. Whatβs happening?
hmmmm
lets try it
thx bro
Do u have an on message listener?
Yes
And u r using @bot.event deco?
Nope
Huh
Client.event
Ah yea that only
(Don't name your commands.Bot instance client please)
Just exchange it with @client.listen()
And it's gonna work
from discord.ext import commands
import random
client = commands.Bot(command_prefix=".")
@client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency*1000)}ms')
@client.event
async def on_ready():
print("Bot is ready.")
@client.command()
async def fate(ctx, member1, member2):
responses = [" will marry ", " will fall in love with ", " will kill ", "will have a fight with ", " will argue with ",
" will hate ", " will become friends with ", " will betray "]
await ctx.send(f'{member1} {random.choice(responses)} {member2}')
@client.event
async def on_message(message):
if message.author == client.user:
return
resp = ["I hope you're feeling ok!", "OK", "it's fine", "download python now btw", "If you need help call childline"]
if message.content.lower().startswith("tianzheng"):
await message.channel.send(random.choice(resp))
here
the commands aren't working is what I'm saying
Code
π
Uh
Ok
from discord.ext import commands
import random
bot = commands.Bot(command_prefix="&")
@bot.listen()
async def ping(ctx):
await ctx.send(f'Pong! {round(bot.latency*1000)}ms')
@bot.event
async def on_ready():
print("Bot is ready.")
@bot.listen()
async def fate(ctx, member1, member2):
responses = [" will marry ", " will fall in love with ", " will kill ", "will have a fight with ", " will argue with ",
" will hate ", " will become friends with ", " will betray "]
await ctx.send(f'{member1} {random.choice(responses)} {member2}')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
resp = ["I hope you're feeling ok!", "OK", "it's fine", "download python now btw", "If you need help call childline"]
if message.content.lower().startswith("tianzheng"):
await message.channel.send(random.choice(resp))
Bro
What
I said to replace event decos, not commands
Ok
Uhhh
Itβs working, but there is a problem where it just says ignoring exception in command None: discord.ext.commands.errors.CommandNotFound: command βpingβ is not found
Weird
Pain.
Tru, tru
U didn't do bot.command() but did bot.command
do you know what .listen() and what .command() are
I know command but not listen
why'd you use it then?
Because @maiden fable told me to
on message blocking commands lol
don't use things if you don't know what it does
then he's right
Ok
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
@velvet tinsel read this
Nvm forgot client doesn't have commands
Still not working
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found
use bot.command()
your using .listen() for your ping command
Whats the error
There is no error
Please tell me how to send an embed and a regular message together.
!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.
It just does nothing
.send("your message", embed=embed)
show me your code
what can i add in serverinfo command?
!d discord.Guild
class discord.Guild```
Represents a Discord guild.
This is referred to as a βserverβ in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guildβs hash.
str(x) Returns the guildβs name.
^
from discord.ext import commands
import random
bot = commands.Bot(command_prefix="&")
@bot.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(bot.latency*1000)}ms')
@bot.event
async def on_ready():
print("Bot is ready.")
@bot.command()
async def fate(ctx, member1, member2):
responses = [" will marry ", " will fall in love with ", " will kill ", "will have a fight with ", " will argue with ",
" will hate ", " will become friends with ", " will betray "]
await ctx.send(f'{member1} {random.choice(responses)} {member2}')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
resp = ["I hope you're feeling ok!", "OK", "it's fine", "download python now btw", "If you need help call childline"]
if message.content.lower().startswith("tianzheng"):
await message.channel.send(random.choice(resp))
ideas xd
Check out the attributes
And methods
That is enough to give you ideas
okkk
did you do &ping
yes
try using listen on your other on_message
Ok
Thanks it works now
π
i used pip install -U git+https://github.com/Rapptz/discord.py command to install discord.py but it installed another version
i wanted to install 2.0
it installed 1.7.3
how to install 2.0 in replit?
^
there should be a requirements file for poetry, you can edit to use v2 iirc
yes there is
i am trying
not working, give me example
didnt work
I created a channel with on_member_join. I want to set permissions for the channel, but I don't know how to get the channel id that I created. Can someone please tell me how to do this?
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a βsecretβ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
This returns the created channel object
Where should I look on this site?
and channel obj. has an id attribute
Click on the top text
It'll take you to that page
Hello i need help
How can i make like a slowmod if i make an command
like:
!beg
[command]
!beg
[Please wait 30m until the command]
@leaden onyx
invalid character from identifier
c= len([c for c in ctx.guild.TextChannels]) is this correct? i want the number of text channels
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'TextChannels'
it would be ctx.guild_TextChannels?
!d discord.Guild.text_channels
property text_channels: List[discord.channel.TextChannel]```
A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
dont use replit then ez
ctx.guild.text_channels*
tnx
@client.event
async def on_message(message):
if client.user.mentioned_in(message):
await message.channel.send("don't disturb me I have work to do just type ***'$help'*** and help yourself") ``` I am using this command to send a message when someone tags the bot , but for some reason this command is blocking all the rest of my commands
is there any other way to do this using ctx?
i mean it is imp for me
!d discord.ext.commands.Bot.process_commands
await process_commands(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the messageβs author is a bot and doesnβt call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
add this coro to the end of you code , or use .listen() instead of an event
can you please tell me where exactly I have to write this?
at the end / or start of you on_message event
can somebody help me ?
guild.news_channel @reef shell how is this?
like this?
wdym
also , you weren't asked to exactly copy and paste it
Idk what you are looking for
what do you want to do exactly
like this?
embed.add_field(name="News channel", value=f"{guild.news_channel}", inline=True)
and what does this command do?
Guild has no such attributes
What is wrong here? Ive been trying to find the error for a while
so that is not possible?ΒΏ
Hey how can I mention all roles name in the guild without all those long ass text? I tried ctx.guild.roles but it gave me a long ass list with IDs and idk what
You can check if a TextChannel is a news channel or not
!d discord.TextChannel.is_news
is_news()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)"): Checks if the channel is a news channel.
tnx
So you can iterate through the TextChannels and get your desired news channel by checking this
any1?
Is there actually any errors here?
anyone know how to get these two things working?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='?')
class Dms(commands.Cog):
def __init__(self, bot:commands.Bot):
self.client = bot
@bot.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(
f'Hi {member.name}, welcome to my Discord server!')
def setup(bot: commands.Bot):
bot.add_cog(Dms(bot))
class Anti(commands.Cog):
def __init__(self, bot:commands.Bot):
self.client = bot
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
if message.content.startswith(f"{self.bot.user.id} or {self.bot.user.mention}"):
await message.channel.send(random.choice(responses))
elif message.author == self.bot.user:
return
in your first code block you have to do @commands.Cog.listener()
@slate swan Thank you very much man it worked
cool
you did self.client = bot, why do you use self.bot later on your code? it doesn't work that way, you have to do self.bot = bot, or use self.client later in your code instead of self.bot
What are 'all those long texts' btw?
[<Role id=900109488609189958 name='@everyone'>, <Role id=900109858139959409 name='Misa'>]
how can I just get the role names?
oh okay
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
example code?
