#discord-bots
1 messages · Page 466 of 1
Why lol
ye
read the license
Well it's his work and his bot it's also open source too so makes sense
I got the unix time of the time I want to show in the footer
^
how to convert unix to datetime
well that means self.last_msg is None
embed.add_field(name="Game", value=ctx.message.author.game)
wdym?
if you look at the logic of your code
mhm
embed.add_field(name="Game", value=ctx.author.game)??
Like 8:24 PM ?
that message appears when the if not serlf.last_msg is true
why message
?
So yes if the msg was not sent by the bot
error is member has no attribute game
So that the bot dose not snipe itself
yes member has no attribute game
there's no game in there
those are all attributes and methods of a member
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User").
`x == y` Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User") instances too.
`x != y` Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User") instances too.
`hash(x)` Returns the member’s hash.
`str(x)` Returns the member’s name with the discriminator.
@client.event
async def on_guild_channel_create(channel):
try:
guild = channel.guild
logs = await guild.audit_logs(limit=6, action=discord.AuditLogAction.channel_create).flatten()
logs = logs[0]
reason = "Created More Channels Then The Limit"
member = guild.get_member(logs.user.id)
await member.kick()
await channel.delete()
except Exception as e:
print(e)
The limit is nnot working the moment i make a channel i get kicked how can i fix it or am i doing something wrong
yeah okay that might be the case, but self.last_msg is None and thus sends "nothing to snipe"
y add a limit for channels lmfao (un-related)
dw i just need to fix this problem
well it literally just looks if there were 6 channels created EVER, it doesn't check the user, it doesn't check times, and just kicks the user that made the last channel
oh
there's no if statements in there
there's nothing being checked
it just blindly kicks the person
how do i make it check the name
time
how much python have you done before?
a bit lol
i do know but idk how to make it check the last audit log
I guess this is for an anti-raid system, more likely to prevent users from spam-create channels. I'm guessing he wants to check if in a range of seconds how many channels were created, and if that exceeds the limit, the raider would get kicked and the channel would be deleted.
the time off it
use for loops and if statements
Please help me, look at my code and tell me please why the music stops suddenly? I will throw off the code in DM
we do not support people in DM
just post your code here
Ok so it gives me the error RuntimeError: Event loop is closed I don't know what to do since I don't were the error starts from plus I am confused with making a secure token btw here is the program ```py
import discord
from discord.ext import commands
from requests import get
import json
import threading
from threading import Thread
import sys
import os
if os.path.exists(os.getcwd() + "/config.json"):
with open("./config.json") as f:
configData = json.load(f)
else:
configTemplate = {"Token": "", "Prefix": "!"}
with open(os.getcwd() + "/config.json", "w+") as f:
json.dump(configTemplate, f)
token = configData["Token"]
prefix = configData["Prefix"]
i=0
client = commands.Bot(command_prefix="!")
@client.event
async def on_ready():
print("!!! Bot Is Online !!!\n")
@client.command()
async def hi(ctx):
await ctx.reply("hi")
@client.command()
async def meme(ctx):
content = get("https://meme-api.herokuapp.com/gimme").text
data = json.loads(content,)
meme = discord.Embed(title=f"{data['title']}", Color = discord.Color.random()).set_image(url=f"{data['url']}")
await ctx.message.channel.send(embed=meme)
runLoop = True
@client.command()
async def inf_meme(ctx):
while runLoop:
content = get("https://meme-api.herokuapp.com/gimme").text
data = json.loads(content,)
meme = discord.Embed(title=f"{data['title']}", Color = discord.Color.random()).set_image(url=f"{data['url']}")
await ctx.message.channel.send(embed=meme)
global i
(i:=i+1)
if i ==(sys.maxsize):
break
@client.command()
async def stop(ctx):
global runLoop
runLoop = False
threading.Thread(target=inf_meme,).start()
threading.Thread(target=meme,).start()
client.run(token)```
bro ik but how do i make it check the auditlog time like the last time there was a channel created thats what i need
naming please
How can i make my embed the avatar of the player being sniped?
Hey @rare saddle!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Using embed.set)thunmbnail()
https://paste.pythondiscord.com/animahulax.py
The music may cut off at any moment
are you using v2.0 already?
!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)
threading module is not suitable with asyncio
Why are you using threading and asyncio?
threading wont work with async function and also mixing threading with async is bad
you're breaching youtube's TOS, you're breaching discord's TOS and you're breaking copyright @rare saddle so you won't get support here
loop.create_task(coro, *, name=None)```
Schedule the execution of a [Coroutines](https://docs.python.org/3.10/library/asyncio-task.html#coroutine). Return a [`Task`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task "asyncio.Task") object.
Third-party event loops can use their own subclass of [`Task`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task "asyncio.Task") for interoperability. In this case, the result type is a subclass of [`Task`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task "asyncio.Task").
If the *name* argument is provided and not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").
Changed in version 3.8: Added the `name` parameter.
thanks but I when I run the code with the bot id it works perfectly fine
not awaiting a coroutine doesn't crash your code but it doesnt run the function
await is asynchronously and btw meme is NOT a loop, because there are no while runLoop: or something there, await would end it instantly. Consider adding a while runLoop:\n <code> to fix the issue.
And don't use globals
and you should use tasks.loop instead
^^ this
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
There are many more people here besides you who can help, but no one forces you, that's why I said that I will throw off the code in DM
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
you are not allowed to support people here who break TOS/laws

Are you saying that music bots are bad? And this is a violation of the law?
violation of TOS of both platforms (youtube and discord) and also a violation of copyright law
Not much people read the TOS of services
making a music bot is like making a radio station. The stations need to get all permissions from every music publisher to use the music in their shows
Then why are there such bots as: Rythm, Groovy
why do you think groovy got shut down?
and i doubt rythm will last much longer
groovy got a CnD from youtube
Groovy works
There's not much to say really, we're not going to help with a project that uses youtube DL simply because it breaks YouTube's ToS
its like making something, another guy copies it and gets popular for it, thats why copyright exists
Whether YouTube takes action against projects is not our concern, but we won't help people break their ToS
is there any way to know why my bot is extremely slow
check for blocking stuff
actually iirc, you could enable debug mode of the event loop and it will show you operations that take some time to execute
im trying to check if someone has nitro with my bot
but it wont work
@bot.command()
async def whois(self,ctx, user: discord.User=None):
if not user:
embed = discord.Embed(title="Your info.", color=0x176cd5)
embed.add_field(name="Username", value=ctx.message.author.name + "#" + ctx.message.author.discriminator, inline=True)
embed.add_field(name="ID", value=ctx.message.author.id, inline=True)
embed.add_field(name="Status", value=ctx.message.author.status, inline=True)
embed.add_field(name="Highest role", value=ctx.message.author.top_role)
embed.add_field(name="Roles", value=len(ctx.message.author.roles))
embed.add_field(name="Joined", value=ctx.message.author.joined_at)
embed.add_field(name="Created", value=ctx.message.author.created_at)
embed.add_field(name="Bot?", value=ctx.message.author.bot)
embed.set_thumbnail(url=ctx.message.author.avatar_url)
embed.set_author(name=ctx.message.author, icon_url=ctx.message.author.avatar_url)
await ctx.send(embed=embed)
else:
embed = discord.Embed(title="{}'s info".format(user), color=0x176cd5)
embed.add_field(name="Username", value=user.name + "#" + user.discriminator, inline=True)
embed.add_field(name="ID", value=user.id, inline=True)
embed.add_field(name="Status", value=user.status, inline=True)
embed.add_field(name="Highest role", value=user.top_role)
embed.add_field(name="Roles", value=len(user.roles))
embed.add_field(name="Joined", value=user.joined_at)
embed.add_field(name="Created", value=user.created_at)
embed.add_field(name="Bot?", value=user.bot)
embed.add_field(name = "Nitro",value = user.nitro)
embed.set_thumbnail(url=user.avatar_url)
embed.set_author(name=ctx.message.author, icon_url=ctx.message.author.avatar_url)
await ctx.send(embed=embed)
User object has not attribute nitro
there is no way to accurately tell if a user has nitro
ohh
import menu
c = []
py=1
for emoji in ctx.guild.emojis:
em=discord.Embed(title=f"Bot Emojis [{len(bot.emojis)}]", colour=0xffffff,description=f"{emoji} | `{emoji.name}` | [`{str(emoji)}`]({emoji.url})")
try:
em.set_thumbnail(url=emoji.url)
except:
pass
em.set_footer(text=f"Page {py}/{len(bot.emojis)}",icon_url=ctx.author.display_avatar)
c.append(em)
py+=1
pages = menu.MyMenu(source= menu.MySource(c,per_page=2), timeout=180.0, clear_reactions_after=True, delete_message_after=True)
await pages.start(ctx)
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/features/python.py", line 145, in jsk_python
async for send, result in AsyncSender(executor):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/repl/compilation.py", line 140, in traverse
async for send, result in AsyncSender(func(*self.args)):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "<repl>", line 15, in _repl_coroutine
await pages.start(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/menus/__init__.py", line 967, in start
await super().start(ctx, channel=channel, wait=wait)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/menus/__init__.py", line 707, in start
self.message = msg = await self.send_initial_message(ctx, channel)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/menus/__init__.py", line 963, in send_initial_message
return await channel.send(**kwargs)
TypeError: send() argument after ** must be a mapping, not NoneType
```help??
are you doing one emoji per page...?
where do i enable member intents
developer portal and code
you'd need a third party lib
not discord.py
which?
is there a way to get the lyrics to a song im listening on spotify rn using a bot?
use a 3rd party lib or a fork or dpy 2.0
ok
!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.
!pypi dislash.py
k
No. bot.intents doesn't return a discord.Intents object, but you can do bot.intents = discord.Intents.default().
thanks
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/container/bot.py", line 102, in on_message
users = json.load(f)
File "/usr/local/lib/python3.9/json/init.py", line 293, in load
return loads(fp.read(),
File "/usr/local/lib/python3.9/json/init.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python3.9/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Does this mean theres something wrong with my import or with my code?
!JSON
When using JSON, you might run into the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This error could have appeared because you just created the JSON file and there is nothing in it at the moment.
Whilst having empty data is no problem, the file itself may never be completely empty.
You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.
Different data types are also supported. If you wish to read more on these, please refer to this article.
Ah
ok
if message.channel.is_private:
AttributeError: 'TextChannel' object has no attribute 'is_private'
This function should be working right?
hm
How do I properly call the methods contained within some Cog for example Cog B within the methods of Cog A?
!d discord.TextChannel the methds and attributes of text channels are here press the hypelink
class discord.TextChannel```
Represents a Discord guild text channel.
`x == y` Checks if two channels are equal.
`x != y` Checks if two channels are not equal.
`hash(x)` Returns the channel’s hash.
`str(x)` Returns the channel’s name.
Please tell me how to get a client_id spotify?
@zenith zinc what?
Kiss command
Got an issue where bot.getguild(id) returns no guild object.
Any ideas?
We ain't here to spoonfeed
bot = commands.Bot(command_prefix="/", intents=discord.Intents.all())
GUILD = bot.get_guild(getenv("GUILD_ID"))
print(GUILD)
prints None
.|.
Im trying to make my clear command clear for specific users, -clear user amount
how do I make it delete for that user?
!d discord.TextChannel.purge use the check kwarg
await purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own (unless you are a user account). The [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting bot’s messages
Read the examples
so I am trying to make slash commands. After 3 hrs of waiting, still nothing, any ideas why?
Which library?
so use bulk?
from discord_slash import SlashCommand, SlashContext
i have the guild thing
?
Never used that lib, sorry
do I use bulk for the clear
did you sync the commands?
What...?
this
off of slash = SlashCommand(bot, sync_commands=False)
yes
Ah yea. Leave it as it is
in addition, I have
from discord.ext import commands, tasks
and the bot has the create command perm
same here
this one?
yep
okay
i kicked it, then reinvite
any specific error messages you could share?
no, none
i have ben waiting for 3hrs
it's instant if you use the guild's command sync
oh
i have guild thing
like aray with guild id
its int tho
not str
maybe your function isn't right?
An example would be:
@slash.slash(name="example", guild_ids=[guild.id], description="")
async def example(ctx: commands.Context):
await ctx.send(response)
i dont have the square brackets
try with them. Since it takes a list
but it might also just take an int - but not sure
but that is a list
guild is not defined
exactly
yep. In my example, 1 guild id in a list
check if you really have this line:
slash = SlashCommand(bot, sync_commands=True)
yep:slash = SlashCommand(bot, sync_commands=True)
ok
i do get this:```python
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<SlashCommand.sync_all_commands() done, defined at /Users/munmun/opt/anaconda3/lib/python3.8/site-packages/discord_slash/client.py:415> exception=HTTPException('400 Bad Request (error code: 50035): Invalid Form Body\nIn 0.description: Must be between 1 and 100 in length.\nIn 0.options.0.description: Must be between 1 and 100 in length.')>
Traceback (most recent call last):
File "/Users/munmun/opt/anaconda3/lib/python3.8/site-packages/discord_slash/client.py", line 491, in sync_all_commands
raise ex
File "/Users/munmun/opt/anaconda3/lib/python3.8/site-packages/discord_slash/client.py", line 471, in sync_all_commands
existing_cmds = await self.req.put_slash_commands(
File "/Users/munmun/opt/anaconda3/lib/python3.8/site-packages/discord/http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 0.description: Must be between 1 and 100 in length.
In 0.options.0.description: Must be between 1 and 100 in length.
If you want to display very long text you can use a paginator
well, i can shorten it, its fine
If you want to make a paginator 
https://gist.github.com/Rashaad1268/3fcaaef6cc402b026ae09ac9fa6a173a
does anyone know how i can stop the pychache folder from appearing?
This is a question for #python-discussion , last time I asked there I was told it's not recommended
You can ignore that file
what happens if i delete it
would anything happen
how?
nah nothing happens. when you rerun ur bot, it reappears
It will appear again, you won't get any issues
Just ignore that file
my code for loading in the cogs:
for cog in listdir(path.join(path.dirname(path.abspath(__file__)), "cogs")):
if cog.endswith(".py"):
client.load_extension(f"cogs.{cog[:-3]}")
else:
print(f'unable to load {cog[:-3]}') ```
how?
Here is an explanation of that file
https://stackoverflow.com/a/48143622/13953998
you do know you can just use for cog in os.listdir("./cogs") iirc right? 
ive started to get an error sometimes while loading in the cogs
(Not that it makes a difference)
thats not fancy 
AttributeError: module 'discord.ext.commands.errors' has no attribute 'ExtensionFailed'
yeah
error
Lmao
Something else might be causing that error not the __pychache__ folder
i switched from d.py to pycord, but i dont think thats causing the error
according to it, its this line thats causing the error:
client.load_extension(f"cogs.{cog[:-3]}")
thats why forks are bad
bru
make. it. ur. self.
y. e. s.
We are just here to help you fix bugs that u may encounter while make it or clear your doubts, not make it for you
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
thanku
Why does it not load the GIF?
its just loading
and then becomes a poop 🥲 sign
Either the URL is wrong else is a discord issue
Its happening with every GIF
like one month back, i tried the same
and now still it doesnt work
@client.command()
async def emt(ctx):
e = discord.Embed(title="trial Embed", description=" ")
e.set_image(url="https://tenor.com/view/kermit-suicide-flip-jump-crash-gif-5140737")
await ctx.send(content=None, embed=e)
Seems like a discord issue
uh
U gotta set the description to the url
!d discord.Embed.description
The description of the embed. This can be set during initialisation.
when I am using ctx : SlashContext, I am getting this error when using ctx.message.author:python AttributeError: 'NoneType' object has no attribute 'author'
oh ok, thx!
Uh..message sent by bot
If you use a decent IDE you can see the options available
change prefix with chat command pls help dm me
someone tell me how to make an embed?
!embed
Guys it's possible to use any frontend framework with django right?
!discord.embed
ok
Google is your friend
¯_(ツ)_/¯
😦
Just stop
Helppp dm pl
but all of them are random
d ¯_(ツ)_/¯
!d discord.Embed
class discord.Embed(**kwargs)```
Represents a Discord embed.
`len(x)` Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
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/stable/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.
jeez
yes
Lol
Use a database
@zenith zinc make it urself
ok
yea
I figured out the problem. I was using a cog listener for command invocation, but I forgot that listeners won't override the internal library handling of on_message, so I was creating a CustomContext object and invoking a command with it, while the library was creating a normal Context object and invoking a command with it. That's why it looks like the command worked fine, when really it was just being ran twice.
hi
elo
hey
@stark bobcat hi bud
Then message = message sent by the bot
hey! sup
can i ask here if people want to contribute in the creation of my bot ?
i do
which is better sublime or vsc?
Then you should've seen there's no ctx.message.author
class Lobby:
def __init__(self, lobby_number, queue_channel_id, Team_A_channel_id, Team_B_channel_id):
queue_channel = client.get_channel(883963916915453962)
Team_A_channel = client.get_channel(Team_A_channel_id)
Team_B_channel = client.get_channel(Team_B_channel_id)
queue_channel_members = queue_channel.members
queue_channel_members_mention = []
for member in queue_channel_members:
queue_channel_members_mention.append(member.mention)
@client.group(invoke_without_command=True)
async def lobby(ctx):
ctx.send("Lobbies Online.")
@lobby.command()
async def start(ctx):
random.shuffle(queue_channel_members_mention)
team_a = queue_channel_members_mention[len(queue_channel_members_mention) // 2:]
team_b = queue_channel_members_mention[:len(queue_channel_members_mention) // 2]
embed_lobby1 = discord.Embed(title="Teams")
embed_lobby1.add_field(name="Team A", value="\n".join(team_a), inline=True)
embed_lobby1.add_field(name="Team B", value="\n".join(team_b), inline=True)
await ctx.send(embed=embed_lobby1)
it says nonetype doesn't have the attribute members
Command raised an exception: TypeError: 'NoneType' object is not subscriptable what does this mean?
Okay
can u tell me why its not working for me in my case
queue_channel shouldn't be a nonetype
For what line do you get the error
3rd line
How do i read a user's dm
Use fetch_channel
Bot might not have the channel in cache and therefore can't see it
hmm okay
it now says: 'coroutine' object has no attribute 'members'
is there a way to make the bot have the cache, bc it goes on a spiral of problems
Nope
await out of async function, then when do use async it says: init() should return None, not 'coroutine'
Wait, why are your commands even in the init function?
uh.. idk i don't think i intended to do that
um thats weird now that i see it
how can i print the message the has user sent to the bot
Well no but u can dm
It's in the on_message event
So simply message.content
no
It is
dm who ?
E is capital
As I said, it's Embed and not embed
Then you can just check the channel of the message to see if it's in private messages
If (message.channel.type) == "private"
Nope
Maybe
if isinstance(message.channel, discord.channel.DMChannel):
I am a bit rusty
Check the object if it's an instance of the DMChannel object
@slate swan well that's not foor event
It is?
No it's a cmd error handler
why would i do that tho, that is why i asked here
!rule 6
@storm zodiac I don't think u want to get warned by mods bud
it's not ad tho
It is
how is it add
Kind of at least
i have seen other people requesting
in what way ?
Else we have to ping mods
bruh, just tell me a good reason and i will
!rule 6@storm zodiac
The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.
!rule 6
how is it advertising ?
It is
Just leave it
It's not allowed
By now the message can't be seen anymore anyways
It's understandable that you thought to look here for help, but unfortunately we don't allow advertising even for personal projects
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Thanks scofflaw
afaik advertising meant, "use my lib" - "i will pay you" - "this other thing is better i made it"
You may want to listen to the moderator though right?
@client.command(aliases=['ac'])
async def announce(ctx, message):
embed = discord.Embed(
title = '',
description = '',
colour = ctx.author.colour
)
embed.set_footer(text='By oSeatch#6969')
embed.set_author(name=ctx.message.author)
embed.add_field(name='News', value=message , inline=False)
await ctx.send(embed=embed)
await ctx.message.delete()``` My code is supposed to be used in this way
`.announce This is a test`, it will embed `This Is A Test` but right now what it does is emebed `This` because value=message only takes `This` from the message. My question is how do i make take the entire sentence?
Use *
i did
are u replying to me? in which case u mean ctx, message, *?
Yes, take a look at this:
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#keyword-only-arguments
okay, make a command with title, description and color command args, and make an embed and set each embed arg/kwarg to the command input
Advertising is a marketing communication that employs an openly sponsored, non-personal message to promote or sell a product, service or idea.
You were promoting your future product / idea
^
@client.command(aliases=['ac'])
async def announce(ctx, *, message):
embed = discord.Embed(
title = '',
description = '',
colour = ctx.author.colour
)
embed.set_footer(text='By oSeatch#6969')
embed.set_author(name=ctx.message.author)
embed.add_field(name='News', value=message , inline=False)
await ctx.send(embed=embed)
await ctx.message.delete()``` this should work?
Should, yes
al right ill test it
Try it and see ¯_(ツ)_/¯
Hey Krypton
Wow thanks alot @slate swan
Pretty sure this would work too, thanks for the suggestion but ill stick to the smaller code coz im lazy B)
@hollow iron ctx.author.mention
you could make a
author = ctx.author.mention``` and then use `author`
wrong reply ._.
If you use it once it's redundant code though, but yes you can
@slate swan Hey bud
Yes?
Use fetch_member and save it in a variable, and then use .send on it
Well tbh I once advertised my bot in this server and I don't even know that I was warned and after 3 months when I was talking with a mod in modmail he told me I was warned once @slate swan
🤣🤣🤣
@hollow iron api call bud
Without id=
Don't use
..
Don't use fetch
Will have to, if you don't have the members intent enabled
Hey, what does this error mean?
Message: 'Unclosed client session\nclient_session: <aiohttp.client.ClientSession object at 0x7fbcded0d250>'
Arguments: ()
2021-09-12 21:35:46,160 - asyncio - ERROR - Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7fbcded0d250>
Error says it all
Make sure the bot is in the server where the emote is
^
yea .. i did
?
Use both get and fetch.
\🤙
ur emoji small
Like that
\🤙
Yup
ohh
!charinfo 🤙
Copy paste that in your code
\U0001f919: CALL ME HAND - 🤙
Or use the unicode ^
ayee it worked thanksss
pandabweer helo
Hey this should help ```py
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix='!')
@bot.command()
async def DM(ctx, user: discord.User, *, message=None):
message = message or "This Message is sent via DM"
await user.send(message)
bot.run("TOKEN")``` original post was from: https://stackoverflow.com/questions/52343245/python-dm-a-user-discord-bot
Hello
he!!o
that wont work
send_message is no longer a thing
vaprant_id = guild.get_member(672580539513045013) or await bot.fetch_member(672580539513045013)
for the administrator permission would it be ctx.author.guild_permissions.administrator
Oh yeah I will update it sorry
get_member is a method of Guild
not Bot
And you can define the message inside the function.
Wdym was it present previously?
it was a thing some time ago
anyone? ._.
but it was removed
yes
thanks
Can anyone help me with this problem ? Ok so I have fixed my previous error but now it gives me prefix = configData["Prefix"] KeyError: 'Prefix' the prefix that I set is in the config file which is {"Token": "<Bot Token>", "prefix": "!"} here is the code ```py
import discord
from discord.ext import commands
from requests import get
import json
import threading
from threading import Thread
import sys
import os
if os.path.exists(os.getcwd() + "/config.json"):
with open("./config.json") as f:
configData = json.load(f)
else:
configTemplate = {"Token": "", "Prefix": "!"}
with open(os.getcwd() + "/config.json", "w+") as f:
json.dump(configTemplate, f)
token = configData["Token"]
prefix = configData["Prefix"]
i=0
client = commands.Bot(command_prefix="!")
@client.event
async def on_ready():
print("!!! Bot Is Online !!!\n")
@client.command()
async def hi(ctx):
await ctx.reply("hi")
@client.command()
async def meme(ctx):
content = get("https://meme-api.herokuapp.com/gimme").text
data = json.loads(content,)
meme = discord.Embed(title=f"{data['title']}", Color = discord.Color.random()).set_image(url=f"{data['url']}")
await ctx.message.channel.send(embed=meme)
runLoop = True
@client.command()
async def inf_meme(ctx):
while runLoop:
content = get("https://meme-api.herokuapp.com/gimme").text
data = json.loads(content,)
meme = discord.Embed(title=f"{data['title']}", Color = discord.Color.random()).set_image(url=f"{data['url']}")
await ctx.message.channel.send(embed=meme)
global i
(i:=i+1)
if i ==(sys.maxsize):
break
@client.command()
async def stop(ctx):
global runLoop
runLoop = False
threading.Thread(target=inf_meme,).start()
threading.Thread(target=meme,).start()
client.run(token)``` also error occurs in line 22
read the error and the json file
look at the difference
my bad
also thank you
whats bot for
why is this not working 🥲
@client.command()
async def emt(ctx):
e = discord.Embed(title="trial Embed", description=" ")
e.set_image(url="https://tenor.com/view/kermit-suicide-flip-jump-crash-gif-5140737")
await ctx.send(content=None, embed=e)
remove the description kwarg and the content kwarg
what u tryna do?
i see
if message.content.lower() == 'registration complete':
fetched = ctx.guild.get_member(881081223533977630)
print(fetched)
guild = discord.Guild
await my_channel.send('All users registered!')
overwrites = {
def = guild.default_role: discord.PermissionOverwrite(read_messages = False),
guild_me = guild.me: discord.PermissionOverwrite(read_messages = True)
}
if message.author.id not in reg_user:
await my_channel.set_permissions(ctx.guild.default_role, overwrite = overwrites)```
so I've almost got the code working, its just that ``read_messages = False`` is True also for the bot, meaning it can't speak in the channel, how do I get around this?
@client.command()
async def emt(ctx):
e = discord.Embed(title="trial Embed")
e.set_image(url="https://tenor.com/view/kermit-suicide-flip-jump-crash-gif-5140737")
await ctx.send(embed=e)
```like this?
you cant send None
ye
^^ please help with this if you can
what is this def = guild.default_role:
that makes it clear that you don't know basic python
it should work
I should remove that, I was just experimenting bc I was desperate
@client.command()
async def emt(ctx):
e = discord.Embed(title="trial Embed")
e.set_image(url="https://tenor.com/view/kermit-suicide-flip-jump-crash-gif-5140737")
await ctx.send(embed=e)
``` This GIF doesnt load, the embed is successfully sent
normal bug lol
yeah you should learn basic python
def = guild.default_role: discord.PermissionOverwrite(read_messages = False),
guild_me = guild.me: discord.PermissionOverwrite(read_messages = True)
}
``` this is art
for every GIF?
i do know basic python
not every
and you need an instance of Guild not the class itself
I tried like 5
you did, you'd know that you can't assign to keywords
How can i make my bot put a emote in the embed?
also, some fields in an embed need to be added via the embed.set_x methods
Use the emote id
For ex: join 
Yes.
So I just get the id and put it in?
if you're asking about invalid syntax errors, you should review basics
i think ppl know that?
is there smth like ..
bot.wait_for('reaction')?
yes like !ducky_australia
Where do i get the id
???
just keep the emote u wanna keep..
await message.channel.send
So i would do
embed = discord.Embed(title = f"(the id) baaala")
?
message.channel.send
idk if tahts dm..
yeah
thats*
How do i get the id with numbers
y reply?
all i can get is :blaa:
idk y reply
you'd have to do my_user = bot.get_user(your_user_id) and then my_user.send(blah)
use \ before an emoji
ok thx
wut
message.channel.send() just sends your message to whatever channel the original message was sent in
so you have to get the user object of the user you want to DM, then send it to them via the .send() method on that object
its not letting me do /then the emoji
oh wait hang on
member = 696969696969696969
await member.send(672580539513045013, embed= discord.Embed(title="Personal Info Detected!", description=f"{message.author} was banned for an attempt at leaking personal information!", footer="{message}" color=0xff0000))
``` @hollow iron dis maybe
within discord, type the emoji then add a \ before it, then send
nvm i got it
set_image is still not loading the GIF
\
link error lol
no you have to get the user object first
an int has no method .send()
for 3 GIFs?
yes
woh
dont use tenor
I see
true
giphy?
its not saying the emoji its just saying :yes:
@commands.command(name="ssuvote")
async def ssuvote(self,ctx):
embed = discord.Embed(title = f"SSU VOTE", description =f"Vote With the  mark if you plan on attending." "\n" " Put a  if you can not join." "\n" "If you vote with the check you must join when ssu opens if not you will be warned")
embed.set_thumbnail(url = 'https://images-ext-2.discordapp.net/external/jftnVFITYRGaMwbf6aY7Qutqp6Q_2gA4v72nXBbpALg/%3Fsize%3D512/https/cdn.discordapp.com/icons/857793161370533938/c38dde5d462235e12a3e10a2dc789dc6.png?width=461&height=461')
await ctx.send(embed=embed)
is it in the server u got the emoji in
let me check i think so
you were calling .send() on member but member is just the userid, not the user object lol
Yea it is
u sure
wait let me check again
wait can u put emojis in custom descriptions?
oh that happened to me once, i had to get the emoji object and then put it in the string with an f-string
idk why it didn't work with just the id and stuff but
Maybe just make a variable with the emoji id and use an f string
!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/stable/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
def check(reaction, user):
return user == message.author and str(reaction.emoji) == '👍'
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
my_emoji = bot.get_emoji(emoji_id)
await channel.send(f'hello! here is your emoji: {my_emoji}')
I got it
ah alright nice
thanks though
no worries haha
can you help me too?
i've gtg in a minute but if you ask your question someone will probably be able to help!
await my_channel.send('All users registered!')
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages = False),
guild.me: discord.PermissionOverwrite(read_messages = True)
}
if message.author.id not in reg_user:
await my_channel.set_permissions(ctx.guild.default_role, overwrite = overwrites)
print('Non registered users cannot speak')```
what this is doing is that it is preventing non registered users from speaking in a channel, but it is also preventing the bot speaking in the channel
myEmbed.add_field(name='Message:', value=...)
@hollow iron
how do I give permissions to the bot to speak in the channel?
put its id in reg_user ig
tried that though
member_count```
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.members "discord.Intents.members") to be specified.
members```
A list of members that belong to this guild.
discord.guild.members
note that discord.Guild has to be replaced with a guild object
like ctx right?
nothing work im in on member join

like ctx.guild
yep
message.guild
oh
I'm stupid
message.guild.members?
member.guild.members
doesnt work
but your problem is with pillow
so you may send your code
and the error
it don't work doesn't help me in helping you
no, pillow works i just want to add new text
but cant figure out how to def how many members are in guild
member.guild.members should work
send the error
vaprant_id is Nonetype
it returned nonetype
is the guy you want to get in a server with your bot?
then use
discord.Guild.get_member
and you send embeds like
await member.send(embed=myEmbed)
Yup
await ctx.send(random.choice(variable))``` can someone tell me what im doing wrong here
send the error bru
i had it written but i deleted it and saved and now i am forget..
Then we'd need the error
🤦♂️
import random
Yup
ight
but.... a list of pictures?
wouldn't it be in the file kwarg then?
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed "discord.Embed") and it must be a rich embed type.
To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.
its just a crap ton of URLs
also thanks it worked
Good job on helping people 
hi
Hi
if message.content.lower() == 'registration complete':
await my_channel.send('All users registered!')
perms = my_channel.overwrites_for(ctx.guild.default_role)
if ctx.guild.default_role not in reg_user:
perms.send_messages = False
await my_channel.set_permissions(ctx.guild.default_role, overwrite = perms)
print('Non registered users cannot speak')```
ok this is seriously not working
you forgot the id part...
what's the problem with it
oof, I only read the last line
but like
you used the class
not an instance of it
discord.Guild always has to be replaced with a guild instance
message.guild for example
what it does is that it prevents @ everyone from speaking in the channel, but then it also prevents the bot from speaking in the channel which is what Im trying to undo
why don't you give it permission in discord
it has administrative permissions
then it's impossible to prevent it from anything...
but this is an overwrite so no matter what happens, the bot is affected
not if there is an overwrite
Anyone Know How To Make A Bot Command Like If We Do - .delete [channel name] ( not channel mention) it deletes every channel in the server with that name
have you tried writing something there with the bot?
has it thrown an error?
wrong id?
no intents?
!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.
nvm bruh im so stupid
oof

that's a bru moment
should I ask once again
have you enabled intents?
are you sure you have the right id?
are you sure the bot is in a server that the person's in?
Can i not make error codes in cogs? like @test.error
you absolutely can
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.math' raised an error: AttributeError: 'function' object has no attribute 'error'
import discord
from discord.ext import commands
class math(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command
async def add(self, ctx, num1:int, num2:int):
await ctx.send(f"__{num1}__ + __{num2}__ = **__{num1 + num2}__**")
@add.error
async def add_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
em = discord.Embed(title=f"Error!!!", description=f"Incorrect Syntax. Please use **&add <first number> <second number>**", color=ctx.author.colour)
await ctx.send(embed=em)
def setup(client):
client.add_cog(math(client))```
hm
im trying to setup cogs and its my first time doing it, i have no clue where im going wrong
@commands.command()
oh bru
...
stop being so good diabolical
actually, be the best so u can fix my codes, thanks ;DD
!d discord.Guild.get_member
get_member(user_id)```
Returns a member with the given ID.
yeah, idk
intents are both in dev portal and in the code enabled?
stop putting discord in your code
bot tab
there, under
Privileged gateway intents
instantly
and guild is lowercase there
message.Guild
message.guild ✅

otherwise it's even worse
server members intent enabled
now try with message.guild.get_member
guild
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
show me your imports and the bot declaration
@hollow iron
now the bot = commands.Bot stuff
then client
client doesn't take intents.....
!d discord.Client
class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client").
oh, it actually does
intents = discord.Intents.default()
intents.members = true
client = discord.Client(intents=intents)```
or just Intents.default()
since you've imported it
you can
you can delete the from discord import Intents
and paste this in your code
then it should work
if not, I'm done
you're welcome
Hi Guys
I made a simple bot
But Their Command doesn't work
Even I run python program in VS Code
Still...
Anyone Help
import os
import discord
from discord.ext import commands
import random
client = discord.Client()
client = commands.AutoShardedBot(command_prefix="$")
@commands.Bot
async def on_ready():
print('Bot is ready. ')
@client.command()
async def ping(ctx):
em = discord.Embed(title="Pong!", color=discord.Color.dark_blue())
em.add_field(name="bot ping", value=f"{round(client.latency * 1000)}ms")
em.set_footer(text="ping")
await ctx.send(embed=em)
@client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
responses = ['It is certain.', 'It is decidedly so.', 'Without a doubt.', 'Yes - definitely.',
'You may rely on it.', 'As I see it, yes.', 'Most likely.', 'Outlook good.', 'Yes.',
'Signs point to yes.', 'Reply hazy, try again.', 'Ask again later.', 'Better not tell you now.',
'Cannot predict now.', 'Concentrate and ask again.', "Don't count on it.", 'My reply is no.',
'My sources say no.', 'Outlook not so good.', 'Very doubtful.']
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')
This is my code
did not work for while
Someone pls help
Hlo
Anyone help
@copper quartz
Please don't ping random people especially staff.
ok but no one is replying
They were typing now left
btw
I am also Panda but Soul xD
Because typhinting only converts an object to a datatype
if you want it to be optional you'd have to make it a keyword argument with default value None
or whatever default you want
anyone reply mine
if they are all strings, you can't do that
you cannot have a typing.Optional in between arguments if they're all strings
but what you can do is
use each arg with " "
like
"this" "is" "a" "example"
Slash commands allow optional kwargs that allow you to customize it better and have it more user friendly.
there is no error
But when i commands
No reply
Client isn't part of the commands module and thus doesn't recognize commands, so you'd need to make it be bot = commands.Bot() instead of client = discord.Client()
on 6th line?
yeah
ok
if you want to have an optional arg in between a list of args typehinted to strings, there's no way afaik
(considering you don't want slash commands)
I'd recommend reading the error 
hm?
wdym
Look at line 7
The error gives you the exact issue in your code.
Yes, now look at that line, and the error.
this man told me
That's why i did
oh i misread your code lol
you defined client as a Client object and then reassigned it to an AutoShardedBot right after
And he is right you just need to remove every client part and rename it to bot.
heeyy
-__- np lol
hiiiii
yeah try doing this and then if it doesn't work something else is going on
you do run your bot, right?
Ok Will try
bot.run(token)
hiiiu
the mark i did I need to change that Client into bot?
yeah ok
yeah
Ok
You can just do replace all
^
in last line
looks like embedchannels is an int
import os
import discord
from discord.ext import commands
import random
from keep_alive import keep_alive
bot = commands.Bot()
bot = commands.AutoShardedBot(command_prefix="$")
@bot.event
async def on_ready():
print('bot is ready.')
@bot.command()
async def ping(ctx):
em = discord.Embed(title="Pong!", color=discord.Color.dark_blue())
em.add_field(name="bot ping", value=f"{round(client.latency * 1000)}ms")
em.set_footer(text="ping")
await ctx.send(embed=em)
@bot.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
responses = ['It is certain.', 'It is decidedly so.', 'Without a doubt.', 'Yes - definitely.',
'You may rely on it.', 'As I see it, yes.', 'Most likely.', 'Outlook good.', 'Yes.',
'Signs point to yes.', 'Reply hazy, try again.', 'Ask again later.', 'Better not tell you now.',
'Cannot predict now.', 'Concentrate and ask again.', "Don't count on it.", 'My reply is no.',
'My sources say no.', 'Outlook not so good.', 'Very doubtful.']
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')
@bot.command()
async def hello(ctx):
await ctx.send("Hello")
@bot.event
async def on_member_join(member):
print(f'{member} has joined a server.')
@bot.event
async def on_member_remove(member):
print(f'{member} has left the server.')
Fine?
does it work?
how to fix this?
This will still throw the same error
But why is that tho?
Because you need to add the arg command_prefix
what does sharding do? @crimson cliff
and remove bot = commands.AutoShardedBot(command_prefix="$")
you can just compare the two with ==
@round quarry because u can only run 1 at a time
i already did that in 9th lines
1 file*
oh you also need to define your prefix in your first bot = commands.Bot() statement
sure, I run them one by one
how do i convert a int obj in a channel obj?
9th lines should come to 7th lines of code? (Exchange)?
@crimson cliff
i don't think you want an AutoShardedBot while you're still learning the fundamentals of discord.py
He didn't reply.
done that
yes
what do u want
@commands.command(name="Say")
async def say(self, ctx,*, message=None):
await ctx.send(message)
How do i make the bot delete what the person said?
So it delete the say command
So all you see is what the bot said
what does sharding do?
ask others
why?
await ctx.message.delete()
its in ur code right?
thx
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
no
@crimson cliff wym "no"?
Read Dictionary then
its right there in ur code and im asking what doed sharding do?
wut dictionary?
what does no mean
No, I said what did you mean when you said "no".
For my snipe command how can i make it show the person being sniped's avatar?
@commands.command(name="Snipe")
async def snipe(self, ctx: commands.Context):
if not self.last_msg:
await ctx.send("There is no message to Snipe!")
return
author = self.last_msg.author
content = self.last_msg.content
embed = discord.Embed(title=f" Message from {author}", description=content)
await ctx.send(embed=embed)
embed.set_thumbnail(url {author.avatar})??
did u try it yet?
What i just wrote?
yes
ok
When I add that the command dose not work
Ok , is there any web app server with free hosting for discord bots or any other thing and not like free trail but free to use. Please tag me if u want to reply.
You need the url
author.avatar_url
Nothing in life is free
still dose not make the command work
Show me the syntax
haha but actually is there any severs to use for hosting web apps ?
Nothing that i'd recommend some sites are just for testing and slow. The best free hosting will be your own pc.
but I don't want to run it like 24 hours manually but I could make that program is a background process that turns on if the computer is but like I don't know how to do that plus why would I waste my computer memory like five different severs will be using it at the same time so is there a better alternative.
Would you not just go to settings background process and run the file?
When you open your file it will show the power shell and open the terminal
So if you make that terminal run when you open your pc
Thanks
Where do i put that?
I will test it tomorrow kind of feeling sleepy
mhm
@client.event
async def on_message_delete(message):
logchannel = client.get_channel(872911089258598421)
await logchannel.send(f'Message by {message.author} `({message.author.id})` in {message.channel.mention} has been removed. \n**Content**: {message.content}')``` How can I make this tell me how long the message was in the channel for before it was deleted?
Like for example, it was deleted 4 seconds after the message was sent, it would say (4 seconds after message was sent)
ValueError: Circular reference detected what does this means?
!d discord.Message.created_at
created_at```
The message’s creation time in UTC.
message.created_eat
- current time
@client.command()
async def steal(ctx, name=None, emoji:discord.Emoji=None):
if name==None:
name=emoji.name
if len(ctx.message.attachments) > 0 and emoji==None:
stolen=ctx.message.attachments[0]
image = await stolen.read()
await ctx.guild.create_custom_emoji(
name=name,
image=image
)
await ctx.send(f'Emoji {stolen} added with the name "{name}"')
elif emoji.animated:
emoji_url = emoji.url
new_emoji = requests.get(emoji_url)
await ctx.guild.create_custom_emoji(
name = name,
image = new_emoji.content()
)
elif emoji != None:
image = await emoji.url.read()
print(image)
await ctx.guild.create_custom_emoji(
name=name,
image=image)
await ctx.send(f'{emoji} added with the name "{name}".')
Ignoring exception in command steal:
Traceback (most recent call last):
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "d:\INFORMATICA\Discord bot\sefu.py", line 348, in steal
elif emoji.animated:
AttributeError: 'NoneType' object has no attribute 'animated'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'animated'```
help please
emoji is None
no errors
banList must be empty
anyone know whats wrong here coded this ages ago
@bot.command(
name="kick",
help="kick mentioned user",
usage="prefix kick <@member> [reason]"
)
async def _kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.message.delete()
@bot.command(
name="ban",
help="ban mentioned user",
usage="prefix ban <@member> [reason]"
)
async def _ban(ctx, member: discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.message.delete()
just do
if ban in banList:
for ban in banList:
else:
print("banList empty!")
If a list is empty you can just do if
if banList:
# banList is defined
else:
# banList is None (empty)
i just want to send the else part, if the banlist is empty
!d discord.on_message_delete
discord.on_message_delete(message)```
Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the `Client.max_messages` attribute or use the [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event instead.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
how do i define ban here?
then do ```py
if not banList:
return await ctx.send('There are no bans')
doesn't that check if banList exists?
No because we inverse the bool with not
So this says: if banList is empty or None
!e ```py
x = None
if not x:
print('True since we applied not so False will become True')
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
True since we applied not so False will become True
anyone?
nothing is wrong
More info?
does it show an error?
?
error is pretty clear
i have perms tho
ooh ye
should i add return after if not banList?
I have no idea what this is doing.
what are you trying to do?
if not banlist check if there is a ban list in the server when a member leaves the server.
?
for ban in ban list check 2 things when banlist exists
` - if the member is in the banlist it sends a msg saying member was banned
else
member left the sever
so you want to send a message that a member left if a member gets banned?
how many instances are you running
You can make an argument optional by making it a kwarg
Giving it a default value is making it a kwarg
do you know what a kwarg is
so like async def command(ctx, argument = None):
its keyword argument
Well, I guess you could say keyword parameter
everything after , *, is a kwarg
giving something a default value doesn’t make it a kwarg
!e ```py
def foo(*, a): pass
foo()
@hasty 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 | TypeError: foo() missing 1 required keyword-only argument: 'a'
Hmm, interesting
!d discord.ext.commands.Bot.cogs
cogs```
A read-only mapping of cog name to cog.
coglist = self.bot.cogs
for cog in coglist:
cog = self.bot.get_cog(cogname.lower())```
gives a nonetype error for cog
it returns a mapping not a list
a mapping of str and Cog
meaning if you do for name, cog in self.bot.cogs.items() name will be a string and cog will be a Cog object
how do i do buttons command?
@hasty iron Could you take a look, please?
your code doesn’t print anything?
even the first print?
Nope, not even the first print
then the error is coming from Cogs.DryFile
How could I fix it?
i don’t know what error you get
It doesn't show any error from the terminal
it just doesn’t work?
how do i do buttons command?
does the bot run?


