#discord-bots

1 messages Β· Page 484 of 1

misty stream
#

what ? i dont get that code

#

what does it do ?

cloud dawn
#

You just create an async function.

misty stream
#

i have 1

#
@slash.command(
    name='channel',
    description="the bot create a text and voice channel for the member that executes this command",
    guild_ids=test_guilds, options=[
        Option("create", "Enter the Channel Name", OptionType.INTEGER),
        Option("delete", "Enter the Channel Name", OptionType.INTEGER)
    ]
)
async def channel(inter, channelname):
    guild = ctx.guild
    member = ctx.author
    name = 'Custom Channels'
    category = discord.utils.get(ctx.guild.categories, name=name)
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        member: discord.PermissionOverwrite(manage_channels=True , read_messages=True),
    }
    channel = await guild.create_text_channel(channelname, overwrites=overwrites, category=category)
    channel = await guild.create_voice_channel(channelname, overwrites=overwrites, category=category)
    await ctx.channel.purge(limit=1)
cloud dawn
misty stream
#

channel

cloud dawn
#

You can create MORE than oneπŸ₯³

#

🎊 🎊 🎊 🎊 🎊 🎊

misty stream
#

but if i have 2 options so can i assign lets say option create to async def create

#

and option 2 to async def delete

misty stream
#

no cause they will put in a channel name

lusty swallow
#

try the link i linked above

misty stream
#

i will

misty stream
#

ctx = inter

cloud dawn
#

Can't see anywhere where you have done that.

misty stream
#

but i changed it back Xd

#
@slash.command(
    name='channel',
    description="the bot create a text and voice channel for the member that executes this command",
    guild_ids=test_guilds, options=[
        Option("create", "Enter the Channel Name", OptionType.INTEGER),
        Option("delete", "Enter the Channel Name", OptionType.INTEGER)
    ]
)
async def channel(ctx, channelname):
    guild = ctx.guild
    member = ctx.author
    name = 'Custom Channels'
    category = discord.utils.get(ctx.guild.categories, name=name)
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        member: discord.PermissionOverwrite(manage_channels=True , read_messages=True),
    }
    channel = await guild.create_text_channel(channelname, overwrites=overwrites, category=category)
    channel = await guild.create_voice_channel(channelname, overwrites=overwrites, category=category)
    await ctx.channel.purge(limit=1)
#

now you see ctx Xd

cloud dawn
#

You can't just change the arg...

misty stream
#

why not ?

cloud dawn
#

Because no

misty stream
#

if you do instead of arg channel name

#

whyy not

cloud dawn
#

πŸ˜‚

#

Try the code

misty stream
#

ill try

lusty swallow
#

yeah what @cloud dawn said.
That code probably won't work with the error ctx not defined

misty stream
#

it has to be an int can ii change INTEGER to STRING

lusty swallow
#

yes

misty stream
#

it doesnt work

#
Ignoring exception in on_socket_response
Traceback (most recent call last):
  File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_client.py", line 1229, in _on_socket_response
    await self._process_interaction(payload["d"])
  File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_client.py", line 1387, in _process_interaction
    await self._on_slash_command(inter)
  File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_client.py", line 1287, in _on_slash_command
    raise err
  File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_client.py", line 1282, in _on_slash_command
    await app_command.invoke(inter)
  File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_core.py", line 216, in invoke
    raise err
  File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_core.py", line 212, in invoke
    await self._maybe_cog_call(self._cog, interaction, interaction.data)
  File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_core.py", line 37, in _maybe_cog_call
    return await self(inter, **params)
  File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\core.py", line 72, in __call__
    return await self.func(*args, **kwargs)
TypeError: create() got an unexpected keyword argument 'create'```
#
@slash.command(
    name='channel',
    description="the bot create a text and voice channel for the member that executes this command",
    guild_ids=test_guilds, options=[
        Option("create", "Enter the Channel Name", OptionType.STRING),
        Option("delete", "Enter the Channel Name", OptionType.STRING)
    ]
)
async def create(ctx, channelname):
    guild = ctx.guild
    member = ctx.author
    name = 'Custom Channels'
    category = discord.utils.get(ctx.guild.categories, name=name)
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        member: discord.PermissionOverwrite(manage_channels=True , read_messages=True),
    }
    channel = await guild.create_text_channel(channelname, overwrites=overwrites, category=category)
    channel = await guild.create_voice_channel(channelname, overwrites=overwrites, category=category)
    await ctx.channel.purge(limit=1)

async def delete(ctx, channeltodelete):
    guild = ctx.guild
    voicechannel = discord.utils.get(guild.voice_channels, name=channeltodelete)
    textchannel = discord.utils.get(guild.channels, name=channeltodelete)
    if textchannel and voicechannel is not None:
        await textchannel.delete()
        await voicechannel.delete()
    else:
        await ctx.send(f'No channels named, "{channel_name}", was found if you think this was an error please contact the staff using Dm support')
#

i want to assign option create to the create function Xd

heavy radish
#

For embeds, where can I find the code for color?

lusty swallow
unkempt canyonBOT
#

class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)").

There is an alias for this called Color...
misty stream
lusty swallow
misty stream
#

oh

#

what does it do ?

lusty swallow
#

it just tells you kind of variable it expects

misty stream
#

oh

lusty swallow
#

it's not an option to pick from

misty stream
#

damn that would have been cool tho

#

like /channel create channelnamehere

#

to create a channel

#

and /channel delete channelname here

#

to delete the channel

#

Xd

lusty swallow
#

i mean you can override it by requesting strings instead so you can have any options you want. You have to parse it yourself tho

misty stream
#

i ahve a string atm

#
@slash.command(
    name='channel',
    description="the bot create a text and voice channel for the member that executes this command",
    guild_ids=test_guilds, options=[
        Option("create", "Enter the Channel Name", OptionType.STRING),
        Option("delete", "Enter the Channel Name", OptionType.STRING)
    ]
)
async def create(ctx, channelname):
    guild = ctx.guild
    member = ctx.author
    name = 'Custom Channels'
    category = discord.utils.get(ctx.guild.categories, name=name)
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        member: discord.PermissionOverwrite(manage_channels=True , read_messages=True),
    }
    channel = await guild.create_text_channel(channelname, overwrites=overwrites, category=category)
    channel = await guild.create_voice_channel(channelname, overwrites=overwrites, category=category)
    await ctx.channel.purge(limit=1)

async def delete(ctx, channeltodelete):
    guild = ctx.guild
    voicechannel = discord.utils.get(guild.voice_channels, name=channeltodelete)
    textchannel = discord.utils.get(guild.channels, name=channeltodelete)
    if textchannel and voicechannel is not None:
        await textchannel.delete()
        await voicechannel.delete()
    else:
        await ctx.send(f'No channels named, "{channel_name}", was found if you think this was an error please contact the staff using Dm support')```
#

see : Option("create", "Enter the Channel Name", OptionType.STRING),
Option("delete", "Enter the Channel Name", OptionType.STRING)

lusty swallow
#
@slash.command(
    name='channel',
    description="the bot create a text and voice channel for the member that executes this command",
    guild_ids=test_guilds, options=[
        Option("action", "Enter what to do", OptionType.STRING),
        Option("value", "Enter the value to give to the action", OptionType.STRING)
    ]
)
async def create(interaction, action, value):
#

kinda like this

slate swan
#

if i use asyncio.sleep() will it suspend my other code

#

?

boreal ravine
boreal ravine
heavy radish
#

Ahh, Thanks

fading harness
#

how can i host my discord bot

#

24/7

lusty swallow
slate swan
boreal ravine
fading harness
boreal ravine
lusty swallow
boreal ravine
fading harness
lusty swallow
fading harness
misty stream
slate swan
lusty swallow
slate swan
lusty swallow
#

Heroku is fine but you probably should avoid that.

slate swan
lusty swallow
slate swan
slate swan
# fading harness for free?

its like a membership so your bot can run 24/7 in a server but dont get like a free fake server because its probably malware and it could make your pc a zombie

lusty swallow
misty stream
#

so is there no way to make the options do difrent things ?

heavy radish
misty stream
#

like if option = create :
do thing
else:
do other thing

lusty swallow
misty stream
#

cause that wont look the same would it Xd

#

this looks nice

#

and lets members choose

#

what they want to do

lusty swallow
#

ohh wait so it does allow multiple options lol. I'm stupid sorry

misty stream
#

haha

lusty swallow
#

your original code with 2 options work lol

misty stream
#

yeah Xd

#

but now i want to assign the option to a function

lusty swallow
#

yeah don't know how to sorry

misty stream
#

so it will execute either create or delete

#

np Xd

lusty swallow
#

try looking into subcommands

misty stream
#

i cant find anything that works -_-

drifting arrow
#
    @commands.Cog.listener()
    async def on_raw_message_delete(self,payload):
        print(payload)
        mydiscord = discord.Guild
        async for entry in mydiscord.audit_logs(limit=100):
            deleter = entry.user
        print(f"{deleter.name} deleted message by {message.author.name}.")
```Why won't this work? The error says missing 'self' on the async line.
lament mesa
#

it should be a Guild instance not the class

#

!e ```py
class Foo:
def foo(self): print("foo method")

Foo.foo()```

unkempt canyonBOT
#

@lament mesa :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 | TypeError: foo() missing 1 required positional argument: 'self'
sick talon
#

is it possible that the bot can give role in a different server and the command is used in different server?

drifting arrow
lament mesa
sick talon
drifting arrow
# sick talon oh lol how ?

since my bot is being run on my computer and is in 2 discords, i can just search both. This is why I write my code to be specific to 1 discord.

lament mesa
drifting arrow
#

or to the discord the command was run in

drifting arrow
# sick talon ??

Put your bot in 2 discords.
then run this:

@bot.event
async def on_ready():
    print('Bot is ready')
    print(bot.guilds)
sick talon
#
@client.command()
async def role_add(ctx):
  member = ctx.author
  guild = 856061274244251658
  role = discord.utils.get(guild.roles, id = 856071314740740096)
  await member.add_roles(role)

this didnt work

drifting arrow
#

Is your bot in that guild?

sick talon
drifting arrow
#

Does your bot have the relevant perms?

boreal ravine
#

do you have intents

sick talon
sick talon
hasty iron
#

you need to get the guild object first

#

oops

#

!d discord.Client.get_guild

unkempt canyonBOT
hasty iron
#

wait, does this have the latest docs

#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
hasty iron
#

oh nice

drifting arrow
#
    @commands.Cog.listener()
    async def on_raw_message_delete(self,payload):
        print(payload)
        mydiscord = self.client.get_guild
        async for entry in mydiscord.audit_logs(limit=10):
            #deleter = entry.user
            print(entry)
        print(f"{deleter.name} deleted message by {message.author.name}.")
#

still doesnt work

#

I don't want to have to specify a guild

hasty iron
#

get_guild is a function

drifting arrow
#

oh actually

lament mesa
#

call it

drifting arrow
#

I can specify the guild id πŸ€”

lament mesa
#

and pass in a valid guild id

drifting arrow
#

since payload has the guild id

hasty iron
#

also that would raise 2 errors

#

deleter is not defined and message is not too

drifting arrow
#

That's not the issue atm

hasty iron
#

and why are you using VS for python

lament mesa
#

use word

drifting arrow
drifting arrow
cloud dawn
#

Atleast in word you can give every section of code another font and color the text easier.

#

just pass None

drifting arrow
#
    @commands.Cog.listener()
    async def on_raw_message_delete(self,payload):
        print(payload)
        mydiscord = self.client.get_guild(payload.guild_id)
        async for entry in mydiscord.audit_logs(limit=2, action=discord.AuditLogAction.message_delete):
            print('{0.user} did {0.action} to {0.target}'.format(entry))
```gives an exception.. But it doesn't tell me what it is  ;-;
cloud dawn
#

just pass None

#

Don't delete your message to bump lol

drifting arrow
#

What is tb?

cloud dawn
#

!traceback

unkempt canyonBOT
#

Please provide a full traceback to your exception in order for us to identify your issue.

A full traceback could look like:

Traceback (most recent call last):
    File "tiny", line 3, in
        do_something()
    File "tiny", line 2, in do_something
        a = 6 / 0
ZeroDivisionError: integer division or modulo by zero

The best way to read your traceback is bottom to top.

β€’ Identify the exception raised (e.g. ZeroDivisionError)
β€’ Make note of the line number, and navigate there in your program.
β€’ Try to understand why the error occurred.

To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.

drifting arrow
#

lemme get

drifting arrow
# cloud dawn !traceback

  Message=
  Source=C:\Users\<my name>\Desktop\discordbot\Discordbot\Discordbot\cogs\adminlogs.py
  StackTrace:
  File "C:\Users\<my name>\Desktop\discordbot\Discordbot\Discordbot\cogs\adminlogs.py", line 105, in on_raw_message_delete (Current frame)
    async for entry in mydiscord.audit_logs(limit=2, action=discord.AuditLogAction.message_delete):
  File "C:\Users\<my name>\Desktop\discordbot\Discordbot\Discordbot\Discordbot.py", line 76, in <module>
    bot.run(bottoken)

#

It's running it's just throwing an exception

reef shell
#

what is this?
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

drifting arrow
#
    @commands.Cog.listener()
    async def on_raw_message_delete(self,payload):
        print(payload)
        mydiscord = self.client.get_guild(payload.guild_id)
        async for entry in mydiscord.audit_logs(limit=2, action=discord.AuditLogAction.message_delete):
            print("Hello World")
``` It prints out 'Hello World' twice as expected. But then I get an exception. I could even throw out the log details etc. same error.
pale turtle
cloud dawn
reef shell
pale turtle
#

I am not sure. You got the error you tell me

stone palm
#

how do i use discord activities?

cloud dawn
pale turtle
#

I mean I don't think so

cloud dawn
stone palm
#

is there an official library for it?

#

wait how do i use routes

cloud dawn
stone palm
#

raw api?

cloud dawn
stone palm
#

how do i use the raw api?

drifting arrow
#

Oh guess we're just forgetting me 😦

stone palm
#

requests?

drifting arrow
#

@stone palm the raw discord api?

stone palm
#

yes

cloud dawn
stone palm
#

for activities

stone palm
#

how do i make a simple send message request?

#

with the raw api?

cloud dawn
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

cloud dawn
#

Here is my wrapper

drifting arrow
cloud dawn
drifting arrow
#

D:

leaden jasper
#

How to close dms with everyone

stone palm
cloud dawn
stone palm
leaden jasper
#

Not for myself

stone palm
cloud dawn
#

just define it somewhere and use the function inside it.

hasty iron
slate swan
#

is lavalink against youtube tos?

cloud dawn
hasty iron
#

and here too

            try:
                result = await self.bot.http.request(Route("POST", f"/channels/{voiceChannelID}/invites"), json = data)
            except Exception as e:
``` you can except for `HTTPException` an use `e.code`
#

and your naming is inconsistent

#

sometimes you follow conventions, sometimes not

vital condor
#

hey i was wondering what is wrong with the line 37 in this ```py
import os
import discord
import csv
import random
from discord.ext import commands

client = commands.Bot(command_prefix = '.')

phrases = []
with open("phrases.csv") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
phrases.append(row[1])

client = discord.Client()

@client.event
async def on_ready():
print(f"{client.user} logged in now!")

@client.event
async def on_message(message):
if message.content.startswith("<help"):
await message.channel.send(f"This is turboz a epic beyblade fan .Do not think of me as a bot think of me as a human. I promise I would never take over the world or would I?{message.author} well i am a bot who tells you shower thoughts made by hypreninja or ハむパー忍者 his actual name is karthikeyan and Pro Gamer Tejaji his real name is P.S.N.Tejaji type <thought and <joke")
await message.channel.send("")
elif "<thought" in message.content:
response = phrases[random.randint(0, len(phrases) - 1)]
await message.channel.send(response)
elif "<joke" in message.content:
await message.channel.send(f"this is the best joke webbsite {message.author}ever know to man kind -https://rr.noordstar.me/358eda50")
elif "pls" in message.content:
await message.channel.send(f"lol no more of it {message.author}")
await message.delete()

@client.command()
async def kick(ctx,member: discord.Memeber,*,reason="Tried to swim in lava"):
await member.kick(reason=reason)

@client.command
async def ban(ctx,member: discord.Memeber,*,reason="Tried to swim in lava"):
await member.ban(reason=reason)

my_secret = os.environ['TOKEN']
client.run(my_secret)

stone palm
#

so like this?```py
@commands.command()
async def activity(self, ctx):
await DiscordTogetherUrlGen.create_link(self, vc.id, "youtube")

fading harness
#

hey i want the bot to create invites for me

#

what should i do

vital condor
hasty iron
hasty iron
unkempt canyonBOT
#

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates an instant invite from a text or voice channel.

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

guys

stone palm
#

vc?

hasty iron
#

and why are you expecting both int and str when you only need it to be str

        if not isinstance(option, (str,int)):
            raise TypeError(f"'option' parameter MUST be of type string or integer, not a \"{type(option).__name__}\" type.")
stone palm
#

what object?

hasty iron
#

also {thing!r} exists

cloud dawn
# stone palm vc?
self.togetherControl = DiscordTogetherUrlGen(bot)

...
await self.togetherControl.create_link(ctx.author.voice.channel.id, "youtube")
stone palm
#

ohh yeah

hasty iron
#

!e ```py
a = 'abc'
print(f'a = {a!r}')

unkempt canyonBOT
#

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

a = 'abc'
cloud dawn
#

blanket i didn't make this code i should've said, this is what i use since it works and if it works it works 😌

cloud dawn
#

i have no clue

stone palm
#

:O

hasty iron
#

then where did you get it from

cloud dawn
#

ctrl+c is a powerfull tool

hasty iron
#

makes no sense

cloud dawn
#

git prob

stone palm
stone palm
hasty iron
#

yeah, who made the git

stone palm
#

i mean

cloud dawn
#

it was 2 months ago i don't know lol

stone palm
#

yeah

#

woah

cloud dawn
#

lemme try and search

stone palm
#

yes, pls

cloud dawn
stone palm
#

oh yeah this dude

cloud dawn
#

he has updated the code i see

stone palm
#

whats the latest one πŸ˜‹

#

ok ill better check it out

hasty iron
#

its still as bad

cloud dawn
hasty iron
#

but sorry about that criticism earlier

#

didnt know it wasnt yours

stone palm
cloud dawn
cloud dawn
stone palm
#

yeah, just wanted to try the reworked version lol

hasty iron
#

you could PR

cloud dawn
stone palm
cloud dawn
stone palm
#

(a fork with slash commands & interactions)

#

is that what you mean

#

||or have you stopped coding bots||

steady flume
drifting arrow
#
msg = await self.client.fetch_message(messageid)
``` πŸ€” help?
cloud dawn
stone palm
#

oh

#

cool

slate phoenix
steady flume
drifting arrow
#

How do I grab a message using the message id?

cloud dawn
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

drifting arrow
#

Everything I find doesnt work

slate phoenix
# steady flume whats decorators ?πŸ˜…

Decorators are basically functions that run before a function above the async function you would put @commands.command() and for events you use @commands.Cog.listener()

steady flume
#

aok

#

thank you!

slate phoenix
#

np

drifting arrow
#
msg = await self.client.fetch_message(messageid)
```Anybody able to help me figure this out?
```py
    @commands.Cog.listener()
    async def on_raw_message_delete(self,payload):
        print("----")
        print(payload)
        messageid = payload.message_id
        channelid = payload.channel_id
        msg = await self.client.fetch_message(messageid)
        print(msg)
#

Trying to get the message object using the message id

rare saddle
#

Why does the error occur?

visual island
drifting arrow
#

that doesn't seem right

visual island
#

how

drifting arrow
#

idk. but what is _connection?

visual island
#

discord.ConnectionState

#

it's your bot's cache

#

you can see it in the source code/github

drifting arrow
#

but my bot only caches stuff if it's online

#

I want to be able to say my message id is '889517885960093786'
and get the contents of that message. if my bot goes offline then the cache is missing.

#

It's why I am using on_raw_message_delete

visual island
#

!d discord.TextChannel.get_partial_message try this, but i think this also grabs the message from cache, i might be wrong let me see

unkempt canyonBOT
#

get_partial_message(message_id, /)```
Creates a [`PartialMessage`](https://discordpy.readthedocs.io/en/master/api.html#discord.PartialMessage "discord.PartialMessage") from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

New in version 1.6.
drifting arrow
visual island
#

channel.get_partial_message(messageid)

slate swan
#

i need help on how to use heroku to keep my bot online forever

dawn gale
#

u can use repl to host it in the cloud

#

so it doesnt need a pc to run it all day

honest shoal
#

I made a stats command in my bot, but it is being ignored
Here's the code ```py
@bot.command
async def stats(self, ctx):
guilds = sum(await self.bot.cogs["Communication"].handler("guild_count", self.bot.cluster_count))
channels = sum(await self.bot.cogs["Communication"].handler("channel_count", self.bot.cluster_count))
users = sum(await self.bot.cogs["Communication"].handler("user_count", self.bot.cluster_count))

embed = discord.Embed(title=f"{self.bot.user.name} Statistics", colour=self.bot.primary_colour)
embed.add_field(name="Owner", value=ctx.guild_owner)
embed.add_field(name="Bot Version", value=self.bot.version)
embed.add_field(name="Uptime", value=self.get_bot_uptime(brief=True))
embed.add_field(name="Clusters", value=f"{self.bot.cluster}/{self.bot.cluster_count}")
if ctx.guild:
    embed.add_field(name="Shards", value=f"{ctx.guild.shard_id + 1}/{self.bot.shard_count}")
else:
    embed.add_field(name="Shards", value=f"{self.bot.shard_count}")
embed.add_field(name="Servers", value=str(guilds))
embed.add_field(name="Channels", value=str(channels))
embed.add_field(name="Users", value=str(users))
embed.add_field(name="CPU Usage", value=f"{psutil.cpu_percent()}%")
embed.add_field(name="RAM Usage", value=f"{psutil.virtual_memory().percent}%")
embed.add_field(name="Python Version", value=platform.python_version())
embed.add_field(name="discord.py Version", value=discord.__version__)
await ctx.send(embed=embed)```
honest shoal
# steady flume wdym ignored

it shows
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "stats" is not found

steady flume
#

u use cogs ?

honest shoal
#

nah

burnt wharf
#

How can I get a user’s role (for example Staff)?

slate swan
cloud dawn
unkempt canyonBOT
#

property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [β€˜@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
steady flume
#

lol

steady flume
#

why u use self

cloud dawn
steady flume
#

ik

burnt wharf
full lily
stiff nexus
#
class cog(commands.Cog):

    def __init__(self, bot: commands.Bot):
      self.bot = bot
      self.lch = bot.get_channel(880884925711126558)

          #cmd code
           .......
           .........
          await self.lch.send(embed=em)
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 167, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/nsfw.py", line 122, in pgif
    await self.lch.send(embed=em,view=msgl(ctx))
AttributeError: 'NoneType' object has no attribute 'send'

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

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/features/invocation.py", line 146, in jsk_debug
    await alt_ctx.command.invoke(alt_ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 894, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 176, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
slate swan
#

lmao , why are using a Instance attribute to make a api call ?

slate swan
#

self.bot.get_channel?

stiff nexus
#

ya

stiff nexus
#

'NoneType' object has no attribute 'send'

full lily
#

are you sure the id is correct

slate swan
#
class cog(commands.Cog):

    def __init__(self, bot: commands.Bot):
      self.bot = bot
      self.lch = self.bot.get_channel(880884925711126558)

          #cmd code
           .......
           .........
          await self.lch.send(embed=em)
```returns Nonetype
full lily
#

this could be an intents issue

slate swan
#

what

#

you don't need intents for channels

stiff nexus
full lily
#

oh is it because it is in init

#

so the bot instance isn't even up yet when the cog is loaded

slate swan
#

I've been thinking about that

full lily
#

I'd say that's it

slate swan
#

I don't think that works like that

full lily
#
await self.bot.wait_until_ready()

Could we use ^?

stiff nexus
#

the channel is not cached so it wont work so i cant use in class

slate swan
#

just get it during the command

full lily
#

how come

river walrus
#

Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message

fleet axle
#

hey I have created a spam detection command but it bans member when he spams I don't need ban but if anyone spams the bot should send a message like don't spam or stop spamming
can anyone help?

slate swan
#

just replace the part that ban members with a message?

fleet axle
#
async def on_ready():   
    await client.change_presence(status=discord.Status.online , activity=discord.Game(" =help ") )    
    print("Bot is ready")
    while True:
        print("cleared")
        await asyncio.sleep(10)
        with open("spam_detection.txt" , "r+") as file:
            file.truncate(0)
           



#spam detection

@client.event
async def on_message(message):
    counter = 0
    with open("spam_detection.txt", "r+") as file:
        for lines in file:
            if lines.strip("\n") == str(message.author.id):
                counter += 1

        file.writelines(f"{str(message.author.id)}\n")
        if counter > 5:
            await message.guild.ban(message.author, reason="spam")
            await asyncio.sleep(1)
            print("uh oh")```
fleet axle
#

Can u help?

slate swan
fleet axle
#

AttributeError: 'Message' object has no attribute 'send'

#

this one

#

@slate swan

slate swan
fleet axle
#

ok

fleet axle
slate swan
#

i have a question, i'm trying to do a discord.py bot with GUI with kivy, is that possible? i did a button for turn on the bot, but the app crash.
python file:
py'''
import kivy
import discord
from discord.ext import commands
from discord.ext.commands import bot
from kivy.app import App as app
from kivy.metrics import dp
from kivy.uix.scrollview import ScrollView
from kivy.uix.boxlayout import BoxLayout as box
from kivy.uix.anchorlayout import AnchorLayout as anchor
from kivy.uix.gridlayout import GridLayout as grid
from kivy.uix.stacklayout import StackLayout as stack
from kivy.config import Config
from kivy.uix.widget import Widget
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
from kivy.app import runTouchApp
from kivy.uix.button import Button as button
from kivy.properties import StringProperty

class example(grid):
txt = StringProperty("1")
counter = 0
def init(self, **kwargs):
super().init(**kwargs)
def press(self):
self.counter += 1
self.txt = str(self.counter)
bot = discord.ext.commands.Bot(command_prefix="?")
token = "token"
bot.run(token)
'''

#

how would the bot have a gui on discord?

#

kv file:
<MainWidget>:
Label:
text: "hi"
Button:
text: "world"

<example>:
cols: 3
Button:
text: "try"
on_press: root.press()
Label:
text: root.txt

#

oh , its a app that runs the bot

#

yes

#

can I convert something to discord.Member like
discord.Member(id)

#

I'm dumb

#

nvm

#

the app dont respond

#

the bot is on but the app crash

lofty mulch
#

I just had the biggest waste of time in like, ever

#

I brought the laptop to my uni so I could code while there's nothing happening

#

then I realized that the syntax wouldn't load without internet

#

nor I could actually run it and test the code

#

So I was carrying around this bigass laptop for no reason

drifting arrow
#

Is there any way to check my bots cache?

drifting arrow
lofty mulch
#

and what even is an internet dongle?

drifting arrow
#

This doesnt work tho. You're deleting the messages in the channel not of specific user

lofty mulch
#

oooh, modem

#

I also don't have one

#

I might buy it, though

#

seems like a good idea

drifting arrow
#
    @commands.command()
    async def clear_messages(self, ctx, member: discord.Member, amount=10):
        await ctx.channel.purge(limit=amount, check=lambda m: m.author == member)
#

Clears messages from a specific user

#

Β―_(ツ)_/Β―

#

Someone else told me to do it

#

so i did and it worked.

lofty mulch
#

By the way, how could I catch the error that's crashing my command?

#

Tried doing a few tricks on the terminal, but it also doesn't show up

#

At most, it just shows that it didn't work

drifting arrow
#

Your code editor doesn't crash and throw an error?

lofty mulch
#

Nope, the editor is fine

#

It's just the command itself that seems to crash for some reason

drifting arrow
#

do a try/except and catch the except?

lofty mulch
#

I already did

drifting arrow
#

Does the whole bot crash or just the command not run?

lofty mulch
#
except Exception as e: # Em caso de erros durante o processamento,
                        embed.add_field(
                            name=f'Falha ao recerragar {ext}.' # Erro Γ© anunciado na Embed.
                            value = e # Natureza do erro Γ© declarada no fim da Embed.```
#

The command does run

#

I mean, it shows the initial signs

#

It just seems to get randomly stuck midway through it

drifting arrow
#

Then you get a blank response?

lofty mulch
#

Yep

drifting arrow
#

idk how to fix that. I have that same issue with a line in my code

#

I just do try/catch and pass it

#

ignore it until someone else fixes it for me xD

lofty mulch
#

I can't even ignore it cause it's a major part of my bot

#

and I absolutely hate having to restart vscode to correct whatever is weird with it πŸ˜”

gloomy coral
#

hi

drifting arrow
#

oh lord

#

nothing good ever starts with 'hi'

#

whats the issue @gloomy coral

lofty mulch
#

Lesson learned, never code without having the IDE pointing out the errors

#

Jesus

brazen seal
#

Hello i have problem i do new people join channel and i don't know why in embed user mention look like this :/

drifting arrow
#

I mean, technically it still mentions them πŸ˜›

brazen seal
#

so i can't fix it?

slate swan
#

nope

#

unless you mention them outside the embed

drifting arrow
#

You can change member.mention to member.name

#

or even do member.name (member.mention)

stark bobcat
#
 try:      
            x = await ctx.guild.create_category('Mailer')
            y = await ctx.guild.create_text_channel('Mailer-logs',category=x)
            embed = discord.Embed(title="Setup",description=f"Created a private channel {y.mention}, use ``-accessrole[roles]`` give staff access to the channel.",color=0x1793FC)
            await ctx.send(embed=embed)
        
        except:
            for y.id in all_channels:
                await ctx.send('Bot has already been setup')
                break```
brazen seal
#

what better

#

this?

or

stark bobcat
brazen seal
slate swan
#

it's the same thing

slate swan
#

.mention just literally do the same

drifting arrow
#

i prefer the first one.

slate swan
#

^ same

drifting arrow
#

Now to help @stark bobcat

stark bobcat
drifting arrow
stark bobcat
#

dk how i pasted

slate swan
drifting arrow
#

What is the output @stark bobcat ?

brazen seal
#

How?

slate swan
#

.send(member.mention, embed=...)

stark bobcat
#

but

drifting arrow
#

BUT?

stark bobcat
#

when the channel alrdy exists it does not send "Bot has already been setup"

brazen seal
slate swan
#

discord embeds are fucked when it comes down to mentions

slate swan
#

πŸ€·β€β™‚οΈ

#

it will show the member name

stark bobcat
brazen seal
stark bobcat
#

basically the except does not work

#

how i want it

drifting arrow
slate swan
brazen seal
#

okay

drifting arrow
slate swan
#

other than your cache

stark bobcat
#

wait let me send full code

#
@commands.command()
    async def setup(self, ctx):
        all_channels = []
        for guild in self.bot.guilds:
            for channel in guild.text_channels:
                all_channels.append(channel.id)
             
                   
        try:      
            x = await ctx.guild.create_category('Mailer')
            y = await ctx.guild.create_text_channel('Mailer-logs',category=x)
            embed = discord.Embed(title="Setup",description=f"Created a private channel {y.mention}, use ``-accessrole[roles]`` give staff access to the channel.",color=0x1793FC)
            await ctx.send(embed=embed)
        
        except:
            for y.id in all_channels:
                await ctx.send('Bot has already been setup')
                break```
#

intents is correct

spring flax
#

wow that's a lot of channel ids

stark bobcat
drifting arrow
#

lol

slate swan
stark bobcat
#

but not a lot

#

just 2

spring flax
#

two guilds?

drifting arrow
stark bobcat
stark bobcat
#

if i print it

#

it works

#

eee how do i say this

drifting arrow
#
for guild in self.bot.guilds:
            for channel in guild.text_channels:
                all_channels.append(channel.id)
``` This isn't searching for channels or categories. It's simply storing all channel ids
stark bobcat
#
for y.id in all_channels:
                await ctx.send('Bot has already been setup')
                break```
drifting arrow
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

stark bobcat
#

for y.id in all_channels:
print("correct")

#

when i tried this it worked ^^

drifting arrow
grim oar
#

What isn't working

stark bobcat
#

one min

grim oar
#

!d discord.on_message_delete

unkempt canyonBOT
#

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 [`max_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") parameter or use the [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event instead.

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

Ohh, are you using a class?

#

You

#

I think you are, you have self as first param also you have an instance var self.bot

stark bobcat
#

@drifting arrow

#

look

#
@commands.command()
    async def setup(self, ctx):
        all_channels = []
        for guild in self.bot.guilds:
            for channel in guild.text_channels:
                all_channels.append(channel.id)
                    
 
        x = await ctx.guild.create_category('Mailer')
        y = await ctx.guild.create_text_channel('Mailer-logs',category=x)
        embed = discord.Embed(title="Setup",description=f"Created a private channel {y.mention}, use ``-accessrole[roles]`` give staff access to the channel.",color=0x1793FC)
        await ctx.send(embed=embed)


        for y.id in all_channels:
            print('correct')
            break   ```
drifting arrow
#

Type the command properly.

#

you did setuo not stup

grim oar
#

uhh, are you using the stuff they call "cogs"? (I think you are really using classes or copy pasted from somewhere)

stark bobcat
drifting arrow
#

Lemme modify your code. uno momento

stark bobcat
#

i can't see my keyboard

grim oar
#

well yeah, Bot has a method get_channel but still, you haven't cleared the point, are you using cogs

stark bobcat
#

i am using muscle memory

sterile blaze
#

Im making a discord bot for me and my friends to just stay in vc with since rythm is banned but i was wondering how i could add a loop command

#

i dont have much experience

grim oar
#

for playing music which you don't own?

sterile blaze
#

huh

#

i mean yeah

#

its like a walmart rythm

grim oar
#

no we don't help with those stuff here

sterile blaze
#

i dont really understand but

#

ok?

grim oar
#

!rule 5

unkempt canyonBOT
#

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

drifting arrow
#

@stark bobcat try this

    @commands.command()
    async def adminlogs2(self, ctx):
        all_channels = []
        for channel in ctx.guild.text_channels:
                all_channels.append(channel.id)
             
        
        for i in all_channels:
            channel = self.client.get_channel(i)
            category_exists = False
            channel_exists = False
            if channel.name == 'Mailer-logs':
                channel_exists = True
            if category_exists == 'Mailer':
                category_exists = True

        if category_exists and channel_exists:
            print("Category and channel exists")
        elif category_exists and channel_exists == False:
            print("Category exists but channel does not")
        else:
            print("Nothing exists. We're doomed.")
stark bobcat
#

but not recommended

#

get from spotify library or smth

sterile blaze
#

ill try it out anyways

drifting arrow
#

Did you use the code I sent you?

#

That's your issue

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

grim oar
#

Remove self

drifting arrow
#

want me to make it not cogs ver?

grim oar
#

because you are not using cogs

boreal ravine
#

discordutils doesnt even show its source code and its very slow

#

I wouldnt recommend using it tbh

sterile blaze
#

tbh it doesnt matter that much

stark bobcat
grim oar
#

They also use youtube_dl so that suspicious too

boreal ravine
stark bobcat
#

indeed

boreal ravine
#

is there an error?

drifting arrow
drifting arrow
stark bobcat
#

it's buliding

drifting arrow
#

Omg

#

why so long.

ionic wadi
#

memberban = [
"884475415538835507",
"792125905526456332",
"884703567926145085",
"835879940485808178"
]

@bot.event
async def on_member_join(member):
if member.id is in memberban:
await member.kick()
channel = bot.get_channel(858699731928219668)
await channel.send(f"{member.mention} is automatisch gekickt, dit persoon staat op onze blacklist.")

if member.id is in memberban:
^
Invalid syntax

stark bobcat
boreal ravine
drifting arrow
#

and add a little BM await member.send("Kicked coz banned listed")

boreal ravine
#

whats a bm

stark bobcat
drifting arrow
#

Bad manners

boreal ravine
#

confusion

drifting arrow
#

But you can only send messages if they're in the discord

#

It's optional to be bad manners. Looks less professional.

#

But i'm not a professional person so what do I care? πŸ˜›

stark bobcat
#

wai have to edit code

#

it's bot

drifting arrow
#

fine imma just run it on my discord lol

stark bobcat
#

@drifting arrow

#

is it creating the channel

drifting arrow
#

.r/holdup

cloud dawn
stark bobcat
#

ok

#

ok sir

#

r u using webhook

#

same but i dunno

drifting arrow
# stark bobcat same but i dunno
    @commands.command()
    async def adminlogs2(self, ctx):
        all_channels = []
        all_categories = []
        for category in ctx.guild.categories:
            all_categories.append(category)
        for channel in ctx.guild.text_channels:
                all_channels.append(channel.id)
             
        category_exists = False
        channel_exists = False
        for i in all_channels:
            channel = self.client.get_channel(i)
            if channel.name == 'mailer-logs':
                channel_exists = True
        for i in all_categories:
            if i.name == 'mailer':
                category_exists = True

        if category_exists == True and channel_exists == True:
            print("Category and channel exists")
        elif category_exists == True and channel_exists == False:
            print("Category exists but channel does not")
        elif category_exists == False and channel_exists == True:
            print("Category doesn't exist but channel does exist")
        else:
            print("Nothing exists. We're doomed.")
``` There we go. Searches for the channel and category.
Just replace the prints in the if statements for whatever you want to happen.
boreal ravine
#

put a ctx param then

slate swan
#

add ctx to your cmd params 🀨

drifting arrow
# stark bobcat ok lemma try

you can even remove a few lines.
change all_channels.append(channel.id) to -> all_channels.append(channel)
remove channel = self.client.get_channel(i)
change if channel.name == 'mailer-logs': to -> if i.name == 'mailer-logs':

#

Now back to my adminlogs XD

#

Like 10 more log entries to create \o/

stark bobcat
#

hmm ok thanks lemma test it

#

@drifting arrow

drifting arrow
#

Coz you arent looking for the right category.

#

I always set my category names to lowercase.

stark bobcat
#

oh ok one min den

#

yipee works tysm

drifting arrow
#

No worries

gritty flame
#

how would i get the exact cooldown of a command

reef shell
#

is it possible to get an emoji's guild name where my bot is not a member of ?

gritty flame
#

no

drifting arrow
#
    @commands.Cog.listener()
    async def on_member_update(self, before, after):
        print(f'Before: {before}')
        print(f'After: {after}')
``` Why isn't this working? D: the before and after aren't changing.
high flame
unkempt canyonBOT
#
Nuh-uh.

No documentation found for the requested symbol.

high flame
#

bruh i was guessing

#

let me read docs agaiin

reef shell
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

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

you can get the retry after for a context with Command.get_cooldown_retry_after

#

with a Context arg

high flame
#

sus

reef shell
#

My bot became horny since when

high flame
#

lol

gritty flame
high flame
#

k

gritty flame
#

commands

high flame
#

a command group's subcommands?

#

!d discord.ext.commands.Group.commands

unkempt canyonBOT
#

property commands: Set[discord.ext.commands.core.Command[discord.ext.commands.core.CogT, Any, Any]]```
A unique set of commands without aliases that are registered.
gritty flame
#

yeh

slate swan
#

you dont need to make an api req for that

#

add discord.Member as an argument for the command , and you can use member.avatar_url and member.name

drifting arrow
#

why isn't on_member_update not triggering on status and activity updates?

drifting arrow
#

I have my intents and presence set properly

#

@quartz beacon I've never worked with webhooks so I cant help you

burnt wharf
#

How do I mute someone for a certain amount of time?

drifting arrow
#

and I'm trying to figure out my own shit first πŸ˜›

drifting arrow
burnt wharf
drifting arrow
maiden fable
#

What is the logic behind a paginator?

#

!paste bro

drifting arrow
slate swan
#

can someone help me

drifting arrow
#

@slate swan i guess.

burnt wharf
drifting arrow
#

And then getting the loops to run

#

That's a common question asked here. So I have that code ready

#
    @commands.command(help='[Sends the avatar of the mentioned user.]')
    @commands.is_owner()
    async def avatar(self, ctx, *, member: discord.Member):
        userAvatar = member.avatar_url

        embed = discord.Embed(color = member.color, timestamp = ctx.message.created_at)
        embed.set_author(name = f'Avatar of {member}')
        embed.set_image(url = userAvatar)
        embed.set_footer(text = f'Requested by {ctx.author}', icon_url=ctx.author.avatar_url)
        await ctx.send(embed=embed)
cloud dawn
drifting arrow
#

I had gone 2 days since the last time someone ree'd at me for doing it

#

then you had to go and ree at me 😦

#

Anybody know why on_member_update isn't triggering for statuses/activities? it triggers for everything else

pastel torrent
#

my on_member_join dont work? Anybody know something about that?

drifting arrow
#

@pastel torrent you got intents correct?

pastel torrent
#

whats that mean?

maiden fable
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

drifting arrow
#

!paste

hasty iron
#

!d discord.Webhook.send

unkempt canyonBOT
#

await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., wait=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

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.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be 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 to send.
hasty iron
#

avatar_url

zenith zinc
#

help

#

kk bro

drifting arrow
#

never send token

#

Someone once sent token. was sad day for him.

zenith zinc
#

@client.command(aliases = ["lb"])
async def leaderboard(ctx,x = 1):
users = await get_bank_data()
leader_board = {}
total = []
for user in users:
name = int(user)
total_amount = users[user]["wallet"] + users[user]["bank"]
leader_board[total_amount] = name
total.append(total_amount)

total = sorted(total,reverse=True)    

em = discord.Embed(title = f"Top {x} Richest People" , description = "This is decided on the basis of raw money in the bank and wallet",color = discord.Color(0xfa43ee))
index = 1
for amt in total:
    id_ = leader_board[amt]
    member = client.get_user(id_)
    name = member.name
    em.add_field(name = f"{index}. {name}" , value = f"{amt}",  inline = False)
    if index == x:
        break
    else:
        index += 1

await ctx.send(embed = em)
unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

final iron
#

The bot has systems to try and detect if people sent a token

zenith zinc
#

yes

#

sorry

#

rhis i cant fix

#

@quartz beacon you have idea how fix

drifting arrow
#

you turned name into an int

zenith zinc
#

what

drifting arrow
#

lemme read your code properly hold up

zenith zinc
#

kk bro

drifting arrow
#

client.getuser(id) isn't this suppose to be client.get_user(id)?

zenith zinc
#

ouuuuuuu

#

My mistake sorry

drifting arrow
#

i think that's correct

zenith zinc
#

wait

#

i try

#

no bro

#

no work

stone palm
#

dpy2 has discord activities

zenith zinc
#

and?

stone palm
#

activities is one of the best things

zenith zinc
#

yes

river walrus
#

Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message

slate swan
#

uh

#

!d discord.ext.commands.Bot.on_command_error

unkempt canyonBOT
#

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

The default command error handler provided by the bot.

By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.9)") however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.
slate swan
#
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, your_own_error):
        #code
uneven kettle
#

can someone help pls i get this error message

traceback (most recent call last):
File "c:\Users\maxim\Documents\programs\role updator bot\roblox_bot.py", line 54, in <module>
@client.command(description="Unmutes a specified user.")
AttributeError: 'Client' object has no attribute 'command'

quiet coral
#
import os

client=disnake.Client()
@client.event
async def on_ready():
    print(f"logged in as wass ")

@client.event
async def on_message(message):
    if message.content.startswith('/bitcoin'):
        await message.channel.send('43000')
#

I am getting an error str object not callable can anyone help?

stiff nexus
#

how do i add a link button to the link which is generated in my the cmd code??

dapper cobalt
#

Not in the same cog.

hollow agate
#

Is there a way you can get all the messages of a channel (there's like 100 max messages in total) and throw it into a text file like a ticket channel log?

If so, how can I do that?

quiet coral
dapper cobalt
#

In different cogs.

lone aurora
#
        embed.add_field(name='Tag:', value=role)``` what do i replace role with
minor kestrel
#

How can I make my bot execute an action, for example send a message every day at an exact time?

jade jolt
#

use a loop

jade jolt
#

replace role, with the role??

lone aurora
#

just put like @member

minor kestrel
jade jolt
#

jk <@&role_id> @lone aurora

jade jolt
lone aurora
#

why &role_id

jade jolt
#

u want to mention to role right

minor kestrel
lone aurora
minor kestrel
#

I knwo I can use a loop

#

i asked for other ways

lone aurora
#

so i have to add &?

jade jolt
lone aurora
#

aight

minor kestrel
#

check if ctx.guild.id == ID OF THE SERVER YOU WANT TO RUN THE COMMAND ON

jade jolt
#

isnt there a check for exactly this

minor kestrel
jade jolt
#

could make your own

minor kestrel
#

yes

#

try it

hollow agate
#
@client.command()
async def pp69420(ctx):
    logs = await ctx.channel.history(limit=None).flatten()
    with open('logs.txt', "w") as f:
        f.write(logs)
        f.close()

    await ctx.channel.send(f'{logs}')``` Error: ```py
Traceback (most recent call last):
  File "C:\users\jacob\appdata\local\programs\python\python39\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\jacob\OneDrive\Desktop\Code\Camilla\main.py", line 732, in pp69420
    f.write(logs)
TypeError: write() argument must be str, not list

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

Traceback (most recent call last):
  File "C:\users\jacob\appdata\local\programs\python\python39\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
    await ctx.command.invoke(ctx)
  File "C:\users\jacob\appdata\local\programs\python\python39\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\users\jacob\appdata\local\programs\python\python39\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: write() argument must be str, not list ``` I'm trying to make it to where I get all the messages of a channel into a text file and sending that file. Could I get some guidance, please?
minor kestrel
#

so make an string or cycle through the list and insert all the values inside the file

hollow agate
#

Hmmm

minor kestrel
#

and alse I think they are a list with the message objects not only the content

craggy cloak
#

why i can't add this? pip install pynacl

minor kestrel
#

pip install PyNaCl

#

is this ^

craggy cloak
#

o ok

minor kestrel
#

always check spelling

craggy cloak
#

thx

minor kestrel
#

How can I make my bot execute an action, for example send a message every day at an exact time? (but without using loops if it's possible thx)

hollow agate
#
@client.command()
async def pp69420(ctx):
    logs = await ctx.channel.history(limit=None).flatten()
    with open('logs.txt', "w") as f:
        f.write(f'logs')
        f.close()

    with open('logs.txt', "r") as file:
        await ctx.channel.send(f'Here it is!', file=discord.File(file, "logs.txt"))``` Kinda, I still don't know how to get the contents of the channel into the file, could I get more help on that, please?
minor kestrel
hollow agate
minor kestrel
#

Great 😁

craggy cloak
hollow agate
minor kestrel
lone aurora
#

@jade jolt i tried what you suggested, but this doesn't ping for some reason, im guessing its because of the embed, any fix?

minor kestrel
hollow agate
lone aurora
#

sigh

minor kestrel
hollow agate
hollow agate
#

f.write(logs) doesn't work, so yeah just a bit confused

#
@client.command()
async def pp69420(ctx):
    logs = await ctx.channel.history(limit=None).flatten()
    with open('logs.txt', "w") as f:
        f.write('logs')
        f.close()

    with open('logs.txt', "r") as file:
        await ctx.channel.send(f'Here it is!', file=discord.File(file, "logs.txt"))``` code in case you need it again
craggy cloak
dapper cobalt
unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
hollow agate
hollow agate
craggy cloak
dapper cobalt
#

Do not help him with that.

minor kestrel
hollow agate
#

Oop, oke, sorry

hollow agate
#

Do you know what I should do to make it work?

minor kestrel
#

but this isn't a good practice

#

mainly in this case because the list not only contains the message content but all the object it self

#

so you need to iterate through the list and get the message content of each message and then write it inside the file

hollow agate
#

Doesn't work xd

unkempt canyonBOT
#

Hey @hollow agate!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

β€’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

β€’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

minor kestrel
#

you can also do f'{logs}'

hollow agate
#
@client.command()
async def pp69420(ctx):
    channellogs = await ctx.channel.history(limit=None).flatten()
    logs = str(channellogs)
    with open('logs.txt', "w") as f:
        f.write(logs)
        f.close()

    with open('logs.txt', "r") as file:
        await ctx.channel.send(f'Here it is!', file=discord.File(file, "logs.txt"))``` It doesn't give me the contents of the message
minor kestrel
#

listen

#

you need to get the content of each message

#

because each message is an object

#

you know what objects are?

#

don't you

unkempt canyonBOT
#

Hey @quartz beacon!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

β€’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

β€’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

minor kestrel
#

errors?

#

is client.get_role(ID)

#

role = get(message.server.roles, name='CY Army') I think you've invented this line of code

minor kestrel
hollow agate
#
@client.command()
async def pp69420(ctx):
    await ctx.message.delete()
    with open("file.txt", "w") as file:
        async for message in ctx.history(limit=None):
            file.write(str(message.content + "\n"))

    with open("file.txt", "rb") as file:
        await ctx.channel.send("Your file is:", file=discord.File(file, "transcript.txt"))``` So I was messing around with stuff and this gives me the messages in the channel, how could I flip the messages though since it gives me the most recent to oldest.
craggy cloak
#

🐳

hollow agate
#

write

minor kestrel
#

the 'w' stands for write, like 'r' for read

#

is for indicating what you wanna do

#

yw

minor kestrel
#

think of flipping the list

#

for example

wild oak
#

Can someone help me please

@client.command()
async def beg(ctx):
    await open_account(ctx.author)
    user = ctx.author

    users = await get_bank_data()

    earnings = random.randrange(101)

    embed = discord.Embed(color=0xff7b00, title="{ctx.author.mention}", description="You Got {earnings} Pieces Of Candy! 🍭")  
    embed.set_footer(text="Happy Halloween!", icon_url='https://cdn.discordapp.com/icons/838607169074888744/a999fa5973767b1aaea36a3552e9d0c7.png')
    await ctx.send(embed=embed)
    
    users[str(user.id)]["wallet"] += earnings

    with open("mainbank.json",'w') as f:
        json.dump(users,f)``` Whenever i use the command it shows {earnings} instead of the actual earning thing
hollow agate
#
description=f"You Got {earnings} Pieces Of Candy! 🍭")  ```
wild oak
#

Thank you bro

minor kestrel
#

not only "{var}"

minor kestrel
#

don't knwo

#

TRY IT

lyric moat
#

how to make a bot show what discord badges u have ?

minor kestrel
#

bruh just try it

hollow agate
# minor kestrel you need to think that part by your self

I'll do this later since I believe python has a .reverse function and that'll be fairly easy... How can I make the transcript show who sent the message? ```py
@client.command()
async def pp69420(ctx):
await ctx.message.delete()
with open("file.txt", "w") as file:
async for message in ctx.history(limit=None):
file.write(str(message.content + "\n"))

with open("file.txt", "rb") as file:
    await ctx.send("Your file is:", file=discord.File(file, "transcript.txt"))```
minor kestrel
#

Is as simple as this: TRY EVERYTHING BEFORE ASKING

We are not computer how know if it is going to work, and you aren't going to break you pc by coding (you shouldn't)

wild oak
#

@minor kestrelit worked but with the title it said <@Myid> instead of actually pinging me

minor kestrel
#

see it is as simple as that try it and think why it doesn't works, and after being 2 hours thinking google it and if not come here

wild oak
#

instead of {ctx.author.mention} i should put {ctx.member.mention}

#

or no ctx

minor kestrel
#

πŸ˜‘

wild oak
#

{author.mention}?

minor kestrel
slate swan
#

wat

minor kestrel
#

@wild oak so you can do ctx.author.mention

wild oak
#

thats what i had

#

but it shows the id in the title

minor kestrel
minor kestrel
wild oak
minor kestrel
#

read what the file has and then concat what the file had with what you wanted to write and then overwrite it

wild oak
#
 embed = discord.Embed(color=0xff7b00, title=f"{ctx.author.mention}", description=f"You Got {earnings} Pieces Of Candy! 🍭")  ```
minor kestrel
#

you can't mention in titles

wild oak
#

cant?

minor kestrel
#

can't yes haha

wild oak
#

thats dum lol

slate swan
#

why would you use file.close()

#

in a with statement

minor kestrel
#

nor in footers

slate swan
#

.

#

and return aswell

hasty iron
slate swan
#

😐

minor kestrel
#

@quartz beacon you don't need to close the file in an with statement

hasty iron
#

yea the context manager automatically closes the file for you

minor kestrel
#

because is open while you are using it and then automaticaly closes

slate swan
#
pass
#

!eval

pass
unkempt canyonBOT
#

@slate swan :warning: Your eval job has completed with return code 0.

[No output]
minor kestrel
#

Same as write but "r"

slate swan
#

yeah, it's extremely awkward

minor kestrel
#

The rest think it by your own, need to go

slate swan
#

what I noticed if that I write file.readlines() it won't delete it automatically anymore

#

got me for a month

hasty iron
#

wot

slate swan
#

file.close()
return

#

with open('logs.txt', "r+") as file:

#

would be the correct way to do that

hasty iron
#

why are you even using a txt file

slate swan
#

prodigy

hasty iron
#

you’re pretty much asking for worst divine punishment ever

slate swan
#

I luv you

hasty iron
#

funny joke that makes no sense in this context

slate swan
#

can we stay in context?

hasty iron
#

haha i laughed man

#

anyways you shouldn’t use a text file

#

ok you must be trolling or something

slate swan
#

a text file acting as a database?

pliant gulch
#

Why is there two with open?, and why are you doing file.close()

slate swan
#

that's new

pliant gulch
#

Your using a context manager... Not sure why you are manually closing the file

hasty iron
#

"why did you kill that person" "why not lmao"

slate swan
#

pls use a database like, sqlite3, mongoDB or something that's not a txt file

#

it's obvious that database or more consistent and efficient than a .txt file

hasty iron
#

basically same reasons as why you should not use json as a databse

#

in txt files you have no way of arranging data

slate swan
#

what IDE do you use?

#

i'm starting to think your a troll..

hasty iron
#

dude are you serious

#

you clearly are acting like one

#

and it’s annoying as shit

slate swan
#

please use a database

hasty iron
#

because it’s not for that purpose

slate swan
#

^

#

txt is not for storing large amounts of data, at least i dont think so

hasty iron
#

txt is not for storing data at all

#

yeah an on_message isn’t alot

slate swan
#

I might set up a database on my raspberry....

slate swan
#

it would probably last a day

#

but i switched to just putting it in the main file

unkempt canyonBOT
hasty iron
#

why not

#

then why not

#

why is it

slate swan
#

accept we or at least i wont help..

#

I would....

#

it's not our problem

#

it would just be making more errors for your code

hasty iron
#

so one guy = everyone?

slate swan
#

but it would make his code so complex

#

in the future

#

^^

hasty iron
#

not in the future

#

now and later

#

you’re definitely a troll

orchid raptor
slate swan
#

sqlite3 is so simple to install and use 😹 just install the application off their website

#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

slate swan
hasty iron
#

right toxic is "telling people to do something that’s more efficient and that’s actually going to help them"

#

atleast use json if you’re going for txt or no db

slate swan
#

i did a json test with my bot and it stopped working in 2 days 😹

slate swan
#

json's bad

#

it wouldnt import or get data correctly

#

I mean

brazen seal
#

How i can check if user react to specific bot message?

slate swan
#

people tell that a json is not a database

#

and also that you store things in there

#

which makes me really confused

#

maybe I'm just missunderstanding

pliant gulch
#

You store static data into json

#

static meaning not changing, i.e your bot's token. The playing status etc

slate swan
#

oh nice

pliant gulch
#

At least that is what I would say about json for storing stuff

slate swan
#

that's quite a good explanation

#

https://youtu.be/HGOBQPFzWKo this might have been one of the most USELESS videos i've ever watched

Take your Python skills to the next level with this intermediate Python course. First, you will get a review of basic concepts such as lists, strings, and dictionaries, but with an emphasis on some lesser known capabilities. Then, you will learn more advanced topics such as threading, multiprocessing, context managers, generators, and more.

πŸ’» C...

β–Ά Play video
#

lmao

reef shell
slate swan
#

check their dpy tutorial

#

you would cringe tf out

#

how are arguments an intermediate thing

hasty iron
slate swan
#

I have no complaints about freecodecamp in other languages

#

but like....

#

learn dpy

hasty iron
#

learn python*

slate swan
#

they were speaking a whole bunch of bullshit in that video

reef shell
slate swan
#

did they do that?

#

they said arguments were a difficult thing to learn πŸ’€

#

like WHAT

slate swan
hasty iron
#

that’s not even their dpy vid

slate swan
#

they used client

reef shell
#

Why

slate swan
#

client is for making events

reef shell
#

lmaoooo

#

Wat???

slate swan
#

bot is a subclass of client that has explicit stuff for commands

#

explain how you will get this data

brazen seal
#

How i can check if user react to specific bot message?

full lily
#
  #with open('logs.txt', "r+") as old_file:
  #with open('logs.txt', "w") as file:
# You can write those two on one file. Let me see if i remember how
  with open('logs.txt', "r+") as old_file, open('logs.txt', "w") as file:

??

slate swan
#

your using replit, just use the replit database

reef shell
slate swan
#

then what are you trying to store it for..

hasty iron
#

that can be a privacy breach

full lily
#

it is because with required an indented block and you didn't give it one

pliant gulch
hasty iron
#

storing people’s messages without their consent

slate swan
#

use one with

reef shell
slate swan
#

ummm

brazen seal
slate swan
#

excuse me?

pliant gulch
pliant gulch
#

In the end its all preference, and I personally store my tokens in a yml file

slate swan
reef shell
#

Choice

slate swan
#

I don't store it anywhere else

reef shell
slate swan
hasty iron
pliant gulch
#

Lost as to why people even log messages

#

What am I gonna do with that information?

#

Oh you like saying a certain word cool

reef shell
#

Logging the message count is okay

#

Why the content

#

πŸ—Ώ

slate swan
#

replit db aint even all that bad

#

that's messed up

#

you just cannot change data without deleting the keys and remaking them

reef shell
full lily
#

Take note that even discord doesn't show the content of deleted messages in the audit log. It is against the TOS

hasty iron
#

most code is going to get uploaded to github anyways

slate swan
pliant gulch
slate swan
hasty iron
#

and if your repo is public and has your token visible discord will warn you and unverify that token