#discord-bots

1 messages · Page 517 of 1

steep estuary
#

how i can get info like that ?

slate swan
#

Why turning into APK when you can install Python on a phone?

unkempt canyonBOT
#

@slate swan Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

slate swan
#

...

steep estuary
lilac latch
#

Topgg has their own api

vocal magnet
steep estuary
#

not for discord bot list

slate swan
#

Imagine if I want my friend to run my python bot on his phone as an app (so that the token will not get exposed)

lilac latch
steep estuary
#

:/

#

dblpy will not work?

slate swan
steep estuary
#

saw that is for discord bot list

lilac latch
slate swan
#

That I tried to send but got flagged

slate swan
lilac latch
steep estuary
#

ok :/

#

what is on_dbl_test ?

#

i cannot get voter name?

slate swan
#
"""An event that is called whenever someone tests the webhook system for your bot on Top.gg."""
lilac latch
steep estuary
#

ok

lilac latch
#

Can someone tell how do I check how many servers my bot is in??

slate swan
#

Get the length of the guilds attribute of your bot variable

steep estuary
lilac latch
slate swan
steep estuary
#

?

slate swan
#

Stop the spoonfeed

#

And bot.guilds already gives a list back, so doing list() is useless

lilac latch
slate swan
#

!d discord.ext.commands.Bot.guilds

unkempt canyonBOT
slate swan
#

Already gives a list back

#

So just get it's length

steep estuary
#

:/

#

wait

slate swan
#

And please don't spoonfeed

#

People don't learn with that

lilac latch
steep estuary
#

oo

#

yes

#

i saw it was giving guild id with name and member count

#

so i thought it is a dict

#

:/

#

i didn''t saw [ brackets

slate swan
steep estuary
#

:/

boreal ravine
#

lol

steep estuary
#

if to edit a embed id someone react on it ?

lament mesa
#

client.wait_for

steep estuary
#

i want that that should never end

#

anytime the user can react

#

to change the embed :/

cloud dawn
unkempt canyonBOT
#

discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.

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

payload is the following

#

!d discord.RawReactionActionEvent

unkempt canyonBOT
#

class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
leaden anvil
slate swan
#

Don't come to other channels to ask for help

#

You'll get help there we someone can help you

maiden fable
#

Hey seb

visual island
#

what takes the most RAM usage in dpy? Which cache?

maiden fable
#

Bruh

visual island
maiden fable
#

You just stole my line

visual island
#

youre late potatopopcorn

maiden fable
#

No

#

U just copy pasted pithink

visual island
maiden fable
visual island
maiden fable
visual island
#

so do I..

#

gonna eat..

maiden fable
#

Cya then lol

visual island
#

cya

maiden fable
spare lark
#

please tell me if there is any method by which i can get date and time when server member joined discord

slate swan
#

member.joined_at

#

member has to be a discord.Member object

jade jolt
#

joined discord not server?

#

isnt that member.created_at

#

!d discord.User.created_at

unkempt canyonBOT
#

property created_at: datetime```
Returns the user’s creation time in UTC.

This is when the user’s Discord account was created.
jade jolt
#

@spare lark

slate swan
#

!rule 2

unkempt canyonBOT
slate swan
#

Selfbots are against Discord's ToS

#

Oh you mean safe? Like safe to use?

#

Selfbots are not safe to use, so discum isn't either

#

lol i was trying to make a music bot in python (how original) and got this error :(

#

ClientException: ffmpeg was not found

#

Have you even installed it

#

pip install ffmpeg?

#

yes

#

No lol

slate swan
slate swan
slate swan
#

ooh, thx

#

Do you even plan on using youtube_dl

#

!ytdl

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)
slate swan
#

i knew someone was gonna do the command when you said "youtube_dl"

#

ffmpeg can also be used to play mp3 that doens't use youtube

#

So pretty much irrelevant tag above

#

Could you now remove it to not flood the chat with an unnecessary tag @slate swan ? Thanks.

#

so if i make a music bot, ffmpeg or ytdl? or both possible?

#

Don't make a music bot that relies on YouTube

#

It's against their ToS and if your bot gets popular it will be forced to be shutdown like other bots.

#

And all your work will be wasted ¯_(ツ)_/¯

#

yea but none of my bots get popluar lol, so im not worried

#

Doesn't matter

#

Respect the ToS

#

And we won't help you any further about it anyways

#

im like the other thousands of ppl that dont even read the tos lmao

#

bro who even reads the yt tos? like 8 people

#

ik

placid skiff
slate swan
#

^^^^^^^^^^

slate swan
#

but not me i still have music commands

#

ez lyf hack, dont publish ur bot to top.gg

#

its a private bot for me and my closest friends only

#

which will soon die at christmas cuz the code has gone uhh to complicated somethings i dont even know how i did it

#

youtube gets ddos attacks almost everyday, one or two undetected streams wont make a difference lol, but if your bot becomes popluar it is issue

#

Again

#

We don't provide help for that

#

Now feel free to make a music bot on your own

#

i alr have

#

Not you.....

#

thats what the docs are for

#

ohh

#

maybe i should sleep im starting to see things

#

does anyone know why the bots pfp is green (like its talking), when it joins a vc

placid skiff
#

Btw i heard that discord is making something like a music bot themself, so it is not even use to create it

slate swan
#

"ive heard" 🤓

slate swan
#

They don't do a music bot

#

It's an integration/activity

#

YouTube Together

placid skiff
#

🥴

slate swan
#

Just like Discord is implementing games in voice channels

#

i hope they make an api thing where it charges ads from ur account and if u have premium idk, something

terse owl
#

@unkempt canyon

#

Hi guys

maiden fable
#

Hi

stoic ether
#
bot_token = '6qrZcUqja7812RVdnEKjpzOL4CvHBFG'
#

isnt working

slate swan
#

1st you have to bot.run(bot_token)
2nd you just revealed your bots token and now everyone can see and use it

#

This is not a valid bot token

#

Use the correct token

#

No?

slate swan
#

No?

#

i knew someone would try

#

It's just common knowledge that a token is not that short

#

And doesn't have this type of structure

slate swan
#

No need to be Sherlock Holmes for that

#

And I believe this is a client secret

#

ive seen similar tokens like that

#

Random guess though

#

since i spam regenerate token quite alot

#

Bot tokens are not that small and don't look like that

#

ive seen similar

#

Client secrets

#

Those are not tokens

#

I can fully assure you tokens don't look like that

#

you cant know for sure until you try

#

I am sure though

#

what if your wrong?

#

I am not

#

Tokens have a STRUCTURE

#

That always look the same

#

And this token does not have it

#

No need to be Sherlock Holmes

#

i tried it worked

#

your wrong

jade jolt
#

bruh

slate swan
#

jk lmao

jade jolt
#

if it was valid the Python bot would delete it

slate swan
#

It's just not valid, as simple as that

jade jolt
#

i knooooow

slate swan
#

It's eventually a client secret, but not a bot token

jade jolt
#

yes im sure everyone knows that

slate swan
#

Not really no

jade jolt
#

it was sarcasm :|

keen talon
warm flame
grand oracle
warm flame
#

bruhhh

#

what am i suppose to use? nextcord

slate phoenix
#

Discord.py isn’t broken yet you can continue to use it

warm flame
#

i dont want to take risks tho

#

since its not supported anymore it wont have the new features that other apis have?

hasty iron
#

alternatives: none cuz all trash

warm flame
#

ik thats what ive been thinking

#

like im not going back to discord.js

hasty iron
#

then stick with dpy

warm flame
#

but i what if discord announces like a cool new feature

hasty iron
#

then switch libs

warm flame
#

nextcord? pycord?

hasty iron
#

libs, not forks

#

those are forks

warm flame
#

oh yeaa

hasty iron
#

which are trash

slate phoenix
#

I wouldn’t be worried about that I’d be more worried when they Introduce message intents

warm flame
#

do i have to rewrite all my code that i spent like 2 weeks on?

hasty iron
#

2 weeks isnt much

#

you can easily rewrite it

warm flame
#

aight

boreal ravine
slate swan
#

Well, the way the permissions would work in the future of slash commands makes me want to move to slash commands either way

wispy spade
shut axle
#
@client.command()
async def gcreate(ctx, time=None, *, prize=None):
  if time == None:
    return await ctx.reply("⌚ Please include a time!", delete_after=4)
  elif prize == None:
    return await ctx.reply("🏆 Please include a prize!", delete_after=4)
  
  embed = discord.Embed(
    color=discord.Color.blue(),
    title="__New Giveaway!__\n\n",
    description=f"\n\n**Hosted By:** {ctx.author.mention}\n**Prize:** {prize}"
  )
  time_convert = {"s":1, "m":60, "h":3600, "d":86400}
  gawtime = int(time[0]) * time_convert[time[-1]]
  embed.set_footer(text=f"Ends In: {time}")
  gaw_msg = await ctx.send(embed=embed)
  await gaw_msg.add_reaction("🎉")
  await asyncio.sleep(gawtime)
  new_gaw_msg = await ctx.channel.fetch_message(gaw_msg.id)
  users = await new_gaw_msg.reactions[0].users().flatten()
  users.pop(users.index(client.user))
  winner = random.choice(users)
  await ctx.send(f"**GG! {winner.mention} has won: `{prize}`**")

It is not showing the winner message...

slate swan
#

Errors?

shut axle
#

no.

slate swan
#

What have you tried so far?

shut axle
#

It is send the embed and I click the reaction, after like for example i set the time to 10s and I wait with no respond..

slate swan
#

So you didn't tried to fix it by yourself, nothing new

#

Have you tried printing gawtime?

shut axle
#

no...

fading harness
#

hi

steep estuary
#

how to remove all reactions from a message?

slate swan
#

!d discord.Message.clear_reactions

unkempt canyonBOT
#

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

Removes all the reactions from the message.

You need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to use this.
steep estuary
#

ok

shut axle
#

Why it is show me this?

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import discord
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/__init__.py", line 25, in <module>
    from .client import Client
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 27, in <module>
    import asyncio
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncio/__init__.py", line 21, in <module>
    from .base_events import *
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncio/base_events.py", line 296
    future = tasks.async(future, loop=self)
                   ^
SyntaxError: invalid syntax
maiden fable
#

What's your dpy version?

#

Try updating both dpy and Python

slate swan
#

Has nothing to do with that

#

It's invalid syntax

#

So wrong code

maiden fable
#

Eh, the code is just import discord
Nothing else

maiden fable
#

isn't that what I said Yea, probably that

shut axle
#

What is the code for that?

slate swan
#

There's no code

shut axle
#

command*

slate swan
maiden fable
hasty iron
shut axle
#

I have python 3.9

slate swan
#

quick question - I am making bot for 1 specific server, how can I make a command such that it only works in 1 specific channel

#

No you don't

#

At least you don't use Python 3.9

unkempt canyonBOT
#

Custom Command Checks in discord.py

Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:

from discord.ext.commands import check, Context

def in_any_channel(*channels):
  async def predicate(ctx: Context):
    return ctx.channel.id in channels
  return check(predicate)

This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).

The check can now be used like any other commands check as a decorator of a command, such as this:

@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
  ...

This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.

slate swan
#

hmm thanks

shut axle
slate swan
odd walrus
#
import discord
from discord import ext
from discord.ext import commands

token = ""

client = commands.Bot(command_prefix=">")

channel_id = client.get_channel(id)

@client.event
async def on_ready():
        print("Script Started!")
        print(client.user.name)


@client.event
async def on_message(message):
        user_message = (message.content)
        if user_message.lower == 'abc':
                await discord.TextChannel.edit(channel_id, name = "test")

client.run(token)

anyone know how to change channel name?

slate swan
#

That's now how it works

#

discord.TextChannel represents a channel object

#

And you shouldn't just copy paste that in your code as it will never work

#

!d help

unkempt canyonBOT
#

help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3.10/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3.10/faq/programming.html#faq-positional-only-arguments).

This function is added to the built-in namespace by the [`site`](https://docs.python.org/3.10/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
slate swan
#

I need button code 🙃

floral jacinth
#

what's the import to use get in channel = get(guild.channels, name = 'members')?

hasty iron
#

from discord.utils import get

#

but you shouldnt

#

just use discord.utils.get

slate swan
#

@hasty iron whats code for buttons

floral jacinth
hasty iron
#

thats a very vague question

hasty iron
#

thats all you need

slate phoenix
floral jacinth
slate phoenix
#

yep

shut axle
#

no error

blissful narwhal
#

hey i am trying to make a command like prefix+suggest suggestion for dm of bot..if bot will get this so this message forward to owner for suggestions..how can i do can anyone help on this

slate phoenix
final iron
blissful narwhal
slate phoenix
#

yeah the bot can take that message and dm it to you

haughty sedge
#

Will my bot get rate limited if i fetch the name, member count, owner, guild id, of all the servers my bot is in (89) i want it for statistical purposes and to remove bot from ghost servers

slate phoenix
#

You’re only fetching the guild object but I would use bot.get_guild anyways

valid galleon
#

so im making an afk command, and when i use the command, it pings me(i ran the command), but while setting the embed thumbnail, it uses its own pfp. and i believe its setting its OWN afk, not mine. this is my code:

    @commands.command()
    async def afk(self, ctx, *, reason = "No Reason Provided"):

        member = ctx.author
        if member.id in afks.keys():
            afks.pop(member.id)

        else:
            try:
                await member.edit(name = f'[AFK]{member.display_name}')
            except:
                pass



        afks[member.id] = reason



        embed = discord.Embed(title = "AFK Set", description = f'{member.mention}, I set your AFK.', colour = member.colour)
        embed.set_thumbnail(url = member.avatar_url)
        embed.set_author(name = self.client.user.name, icon_url = self.client.user.avatar_url)
        embed.add_field(name = 'AFK Note:', value = reason)

        await ctx.send(embed = embed)```
haughty sedge
#

im iterating through all the guilds my bot is in and putting guild.name and other info

slate phoenix
#

I’d try using get_guild and if the bot is returning None then I would use fetch_guild but maybe sleep it per a guild just to be safe

haughty sedge
#

hmmm

shut axle
#

No errors.

haughty sedge
# shut axle **__Why it is never show the winner? __**

try to host giveaway for few seconds and ask 2-3 friends to participate if you're too low on members then remove users.pop(users.index(client.user)) then ur bot can also declare itself as winner, this statement only removes ur bot from giveaway. Make sure not to re-run the code as you're using asyncio.sleep() which is too bad and whenever ur bot is restarted then the code executing gets stopped and winner wont be declared

night onyx
#

can anyone tell me how can i compare two permissions and decide by it which permission is greater i mean which has greater priviledges

shut axle
hasty iron
#

a database

#

and a task

#

store the time it began and the time it will end

#

keep adding to the time it began until it reaches the end time

#

then announce a winner

slate swan
#

can somebody tell me how this actually works?

#

its from discord application page

hasty iron
#

thats not python

slate swan
#

oh

hasty iron
#

its c or c++

slate swan
#

ye you are right

night onyx
#

whats this about

haughty sedge
# shut axle what should I use instead of `asyncio.sleep()` ????????????

nothing, giveaway is an intermediate command if you dont want to reset the value on restarting there are two things you can do
1)Code the giveaway command seperately and seperately host it so u can change other code and reboot other code but not the giveaway one. Its nto a good idea
2)This idea is much better use database and check it whenever bot is rebooted

night onyx
#

can anyone tell me how can i compare two permissions and decide by it which permission is greater i mean which has greater priviledges

slate swan
floral jacinth
#

how do i get name of a role by giving the id?

haughty sedge
hasty iron
#

!d discord.Guild.get_role

unkempt canyonBOT
hasty iron
unkempt canyonBOT
hasty iron
#

imo java is similar to clangs

haughty sedge
#

but C# is not that badly hard and quite similar to java

#

i think my java skills is now more than python lol

floral jacinth
hasty iron
#

its a method of Guild

slate swan
#

but does anyone know about what i sent before

hasty iron
#

not Context

slate swan
#

?

floral jacinth
#

damn

hasty iron
#

there is a python lib for it

#

!pypi pypresence iirc

unkempt canyonBOT
boreal ravine
#

is c# called c or cs or csharp

hasty iron
#

C is not C#

#

C# = csharp

floral jacinth
hasty iron
floral jacinth
#

yup

boreal ravine
#

hm

slate swan
hasty iron
#

what

#

thats a library, you install it and use it

slate swan
#

so this?

hasty iron
#

i wonder where i can find a big pip install pypresence hmmmm

slate swan
#

hi, i want to make a check for a ticket system, so if someone already has a ticket open by the name for instance: ticket-rebellion that it would check if the channel exists, and if it does it won't let them open another ticket, but if it doesn't it'll open a ticket

slate swan
boreal ravine
#

@hasty iron Pypi has a dark mode?

haughty sedge
#

how to fetch the list of all persons connected to a voice channel

hasty iron
boreal ravine
solemn grove
#

How to create a stiky message?

valid galleon
#

im making an afk command, but when i use it, it says it set my afk, but then immediately removes it. this is my code:

    @commands.command()
    async def afk(self, ctx, *, reason = "No Reason Provided"):

        member = ctx.message.author
        if member.id in afks.keys():
            afks.pop(member.id)

        else:
            try:
                await member.edit(name = f'[AFK]{member.display_name}')
            except:
                pass



        afks[member.id] = reason



        embed = discord.Embed(title = "AFK Set", description = f'{member.mention}, I set your AFK.', colour = member.colour)
        embed.set_thumbnail(url = member.avatar_url)
        embed.set_author(name = self.client.user.name, icon_url = self.client.user.avatar_url)
        embed.add_field(name = 'AFK Note:', value = reason)

        await ctx.send(embed = embed)



    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.id in afks.keys():
            afks.pop(message.author.id)
            try:
                await message.author.edit(nick = remove(message.author.display_name))
            except:
                pass
            embed = discord.Embed(title = f'Welcome back', description = f'Welcome Back, {message.author.name}! I removed your AFK')
            await message.channel.send(embed = embed)

        for id, reason in afks.items():
            member = get(message.guild.members, id = id)

            if(message.reference and member == (await message.channel.fetch_message(message.reference.message_id)).author) or member.id in message.raw_mentions:
                embed = discord.Embed(title = 'Member AFK', description = f'{member.name} is currently AFK.\nAFK Note: {reason}')
                await message.reply(embed = embed)```
slate swan
slate swan
#

Iterate through all the channels and check for the channel name

slate swan
#

If done correctly it does work

slate swan
keen talon
unkempt canyonBOT
#

discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Examples

Basic usage...
ripe jackal
#

Hello, can someone help me? I got this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'server'
by trying to create reaction roles embed message. Can someone tell me what to do pls? Here is the code:```python
@client.command()
async def rr(ctx):

channel = client.get_channel(892014899587342356)
user = ctx.author
role = discord.utils.get(ctx.author.server.roles, name="✅ Verified")
em = discord.Embed(title='✅ Verify', color=discord.Color.green())
msg = await em.channel.send(embed=em)
await msg.add_reaction("✅")
await user.add_roles(user, role)```
valid niche
#

Also just do ctx.guild

#

No need for the author in between

#

Can only cause more issues

ripe jackal
#

okay, but how do i enter the exact channel

#

should i do guild = client.get_channel(892014899587342356)?

slate swan
#

no, you should do myInt = "Hello World!"

ripe jackal
slate swan
#

ofc

hasty iron
#

ah yes, guild.guild

ripe jackal
#

can someone help me :p?

glass sail
#

hey
if i hv the id of a message how do i get the message content? (dm channel)

unkempt canyonBOT
glass sail
#

no but i have to fetch the msg

hasty iron
#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

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

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

is there any method by which i can get dash in command name like
$user-info

reef shell
#

aliases

#

name

fallow mauve
#

im wanting to make a verification command, how do i specify a role with a certain name?

slate swan
#
role = discord.utils.get(guild.roles, name=rolename)
fallow mauve
#

can u give me an example of how it would go in the code?

slate swan
#
role = 'verified'
role_obj = discord.utils.get(guild.roles, name=role)
fallow mauve
#

but where in the command?

slate swan
#

right before the code where you assign the role to the user

fallow mauve
#

ok

#

i dont get it

#

d! discord.utils.get

#

!d discord.utils.get

slate swan
#
@bot.command()
async def verify(ctx):
  roles = []
  for role in ctx.author.roles:
    roles.append(str(role))
  
  if "verified" in roles:
    await ctx.send("You're already verified")
  else:
    role = discord.utils.get(guild.roles, name='verified')
    await ctx.author.add_roles(role)
    await ctx.send("You've been verified") 
hasty iron
#

most likely a cloudflare ban

#

or something like that

waxen granite
#

hm

fallow mauve
#

how do i import "guild"?

hasty iron
#

from discord import guild

#

its a module

fallow mauve
#

ok

#

i tried "from discord.ext import guild" and it dont work lol

slate swan
slate swan
#

await

#

if "verified" in roles: not sure

fallow mauve
# slate swan guild = ctx.guild
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 28, in verify
    for role in user.roles:
AttributeError: module 'discord.user' has no attribute 'roles'

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/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.user' has no attribute 'roles'```
#

my error

jade jolt
#

member has roles

#

user doesnt

maiden fable
slate swan
#

I couldn't do the thing I wanted to do 😔

slate swan
slate swan
#

also you might have to change the if 'verified' in roles line

hasty iron
#

that still can be improved

#

discord.utils.get(member.roles, name='verified')

#

save that to a variable and check if its None

#

if its not, they're verified

#

else, add the role

slate swan
#

yeah

fallow mauve
#

"discord.guild has no attribute 'roles'"

hasty iron
#

since i dont think you need the user's role you can just do if discord.utils.get(member.roles, name='verified'):

fallow mauve
#

im so lost

jade jolt
#

u need a map?

fallow mauve
#

-_-

jade jolt
#

:)

fallow mauve
#

might be helpful, idk

jade jolt
#

🗺️ here

hasty iron
fallow mauve
jade jolt
#

lol

#

do u

fallow mauve
#

just never specified a role name before

hasty iron
#

wot

fallow mauve
#

?

hasty iron
#

what does a role name have to do with an attribute error

slate swan
hasty iron
#

what

fallow mauve
hasty iron
#

i mean, didnt azrael spoonfeed you already

fallow mauve
#

if thatd happened i wouldnt be having any problems, also i dont want spoonfed, i want to know why im getting these errors

#

lets start over

slate swan
#

and code

fallow mauve
#

what things do i need to import for this to work?

hasty iron
#

yeah so show your whole code and traceback

#

you dont need to import anything

fallow mauve
#

ok

hasty iron
#

discord.py wont magically define a Guild object for you

#

if you dont know that then you definitely are missing some basics

fallow mauve
#

code:

@Bot.command()
async def verify(ctx):
  roles = []
  for role in ctx.author.roles:
    roles.append(str(role))
  
  if "verified Member" in roles:
    await ctx.send("You've been verified already.")
  else:
    role = discord.utils.get(guild.roles, name='verified Member')
    await ctx.author.add_roles(role)
    await ctx.send("You've been verified")

error:

Ignoring exception in command verify:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 35, in verify
    role = discord.utils.get(guild.roles, name='verified')
AttributeError: module 'discord.guild' has no attribute 'roles'

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/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.guild' has no attribute 'roles'
hasty iron
#

yeah so guild is magically defined inside your function

hasty iron
#

the error is pretty simple and tells you what you should remove

#

!d discord.ext.commands.Context.guild

hasty iron
#

ded bot

fallow mauve
#

lemme read the error again...

hasty iron
#

anyways you can use Context.guild to get a Guild object

slate swan
#

ctx

hasty iron
#

?

slate swan
#

if you... aren't smart

#

he would import Context

#

and use discord.Context.guild

hasty iron
#

very smart

slate swan
#

which would make me cry

#

assuming the last two digits in his username are the last two digits in his birth year, he's doing pretty good for a 12 year old

fallow mauve
#

12?

slate swan
#

11 whatever

glass sail
fallow mauve
slate swan
#

I've been awake for 15 hours, gimme a break

glass sail
slate swan
#

🗿

fallow mauve
slate swan
#

I don't remember

fallow mauve
#

lol

slate swan
#

15 is a guess

fallow mauve
#

ok

slate swan
#

or commands.Context

glass sail
slate swan
#

innit

hardy yoke
glass sail
#

@hardy yoke

hardy yoke
#

you're missing something there

glass sail
fallow mauve
#

i give up for now, my brain hurts, i need to go eat smth

glass sail
#

thanks

blazing vapor
#

how do i fix this error TypeError: 'Int64' object is not subscriptable
my code

    @commands.command()
    async def buy(self,ctx,item_name,amount = 1):
        data = loadf('databases/shop1.json')
        item_name = item_name.lower()
        name_ = None
        for item in data["content"]:
            print(data)
            print(item)
            name = item['id'].lower()
            if name == item_name:
                name_ = name
                price = item['price']
        buyer_money = user_balance.find_one({'_id': ctx.author.id})
        
        buyer_cash = buyer_money['balance']['cash']
        if price > buyer_cash['balance']['cash']:
            await ctx.send('You Don\'t Even Have That Much Money Idiot 😛')
            return
        else:
            user_balance.update_one(buyer_cash, {"$inc": {
                    'balance.cash': -price}})
            user_inventory.insert_one({'_id': ctx.author.id, 'items': {
            name_: amount
            }})
            await ctx.send(f'You have successfully bought {amount} {name_}')```
stiff nexus
#

i have ```py
await c.send(f"{error[:2000]}")

```py
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/", line 939, in on_command_error
    await c.send(f"{error[:2000]}")
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1422, in send
    data = await state.http.send_message(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 335, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In content: Must be 2000 or fewer in length.
slate swan
slate swan
#

so

if role in member.roles:
#

role must be discord.Role obj

fallow mauve
hardy yoke
#

shud work

blazing vapor
#

wdym?

hardy yoke
#

await c.send(f"{error[:1986]}

blazing vapor
#

wat?

hardy yoke
#

? is it not self explanatory lol
Exactly 2k is obviously not working so make it lower.

#

error msg is probably just a bit misleading if sending exactly 2k chars isn't working

simple kettle
#

I want my discord bot to send a embed message every time I upload a video to YouTube, I want the embed message to have the link to the video. Where would I start to make this happen?

dense swallow
#

You should look into an API which does that.

#

That is, that API should fetch the yt notifs

#

And then the easy part connect it to ur bot and send as embed

simple kettle
#

I think I just found one it’s from google

spare lark
#

please tell me how should i put - in command name like this
$user-info

tough wagon
spare lark
#

i'm making command like this
@native granite
async def commandName(ctx):
how should i do in this

tough wagon
spare lark
#

okay

tidal hawk
#

how do ignore bot raw_reactions?

#
        if payload.member is self.client:
            return```?
tough wagon
tidal hawk
#

Basically bot sends a message with thumbs up emoji. And I created a on_raw_reaction_add listener func, which reacts when somebody reacts with thumbs up

crystal wind
#

Is there a guide for Discord 2.0? I'm not really sure how I can do buttons that are interactive.
I'm using discord_components with Discord 2.0, but I've realized it comes in conflicts. What should I do?

tidal hawk
#

whenever the bot sends a message with thumbs up, then the reaction_add func activates aswell

tough wagon
#

if you want to ignore all bots: if payload.member.bot: return, if only your bot: if payload.member == payload.member.guild.me

tidal hawk
#

thanks man!!

brazen raft
#

on_raw_reaction_remove's payload shouldn't have member

tidal hawk
#

it worked

brazen raft
#

awesome

#

they should update the docs lol

tidal hawk
#

welp it only worked on on_raw_reactoin add, not on on_raw_reaction_remove, which makes no sense

#

AttributeError: 'NoneType' object has no attribute 'bot'

brazen raft
#

Well, yeah, according to the documentations, it has to be the on_raw_reaction_add event for it to work

#

read the first line on member there

brazen raft
tidal hawk
#

Represents the payload for a on_raw_reaction_add() or on_raw_reaction_remove() event.

#

member

tough wagon
tidal hawk
brazen raft
tidal hawk
#

how do i work around this then

brazen raft
#

You can check if it's your own client by using paylod.user_id == self.client.id

tough wagon
#

yeah

#

better way

tidal hawk
#

thanks lads!

crystal wind
#

@tough wagon Also do you suggest using discord 2.0 or do you use something else for such things as buttons and slash?

slate phoenix
crystal wind
#

hmmm

#

It feels really weird to use 2.0, I was using discord_components all this time.

#

there's such documentation that really shows an example of creating buttons

placid skiff
#

I use nextcord which is a supported fork of discord.py and has buttons in it

#

I have not used them yet but there are some tutorial on youtube that shows to you how to use them

slate swan
#

How tf do I fix this

crystal wind
#

I saw that discord_components would conflict with discord.py which the buttons won't work on it. I thought I'd just stick to something simple for it.
Although, I'm not sure why people suggest using discord.py (2.0) for such a thing.

slate swan
#

Somebody help I need to make a good impression on somebody and now it's not working

crystal wind
#

i'm not sure what could be the problem there because the edges are cut.

#

I'd assume you forgot to add ":" at the end of your if.

slate swan
#

All of a sudden it's just broken

crystal wind
#

AH

#

try this! (message.content).startswith

#

sorry idk if I know about dis :(

slate swan
#

😭

crystal wind
#

it's not working?

slate swan
#

It's STILL NOT WORKING

crystal wind
#

it says it's a syntax error

slate swan
#

I'm so confused

crystal wind
#

what is it pointing at?

slate swan
#

The :

#

I don't understand why it's invalid

#

Makes absolutely no sense

#

I'm going to restore another version that see if it'll work

#

It's fixed now-

#

I have no idea how

#

😔🔫

crystal wind
#

ah wait

#

that's kinda unfortunate

valid perch
#

Can you send the code here next time possible? Screenshot wasn't the clearest

crystal wind
#

but I assume you want also characters after this

slate swan
#

It's fixed now

crystal wind
#

what happened?

slate swan
#

I think there was something wrong with python itself

crystal wind
#

o

#

that's weird

slate swan
#

There's no difference between the old version and the new one

quiet coral
slate swan
#

!d discord.Member.mention

unkempt canyonBOT
quiet coral
slate swan
#

you don't....

#

it's not a function

crystal wind
#

Is there a way to uninstall discord.py on pycharm? Because I seem to have some trouble out of it

slate swan
#

whichever user/member you use the attribute on is gonna get mentioned

quiet coral
#

can you give an exemple please

slate swan
#
member = ctx.author
await ctx.send(member.mention)
quiet coral
slate swan
#

You get (or fetch if member not present in cache) a member with it's ID

slate swan
#

and then you do yourMember.mention

placid skiff
#

If i want to create a command which can be used both with slash or command prefix i had to declare the command twice or i can just do

@slash.slash()
@bot.command()
slate swan
#

They're separate libraries

valid perch
placid skiff
#

That sounds annoying 😂

crystal wind
#

For some reasons, I tried to use discord_components to prompt a button by using the command !button. However, for some reasons, the await client.wait_for() doesn't seem to work on Pycharm compared to Replit. Is there a reason why?
By the way, I used the same command for both of them. I don't know why is it only the one on Replit that works.

valid perch
#

Welcome to the discord developer experience

placid skiff
#

And i can t even use discord.py embed into slash command i suppose, right?

valid perch
#

Should be able to

crystal wind
#
async def button(ctx):
    await ctx.send("This is a button",
                   components=[
                       Button(label="Nice!")]
                   )
    interaction = await client.wait_for("button_click", check=lambda i: i.component.label)
    await interaction.respond(content="Button Clicked.")```
#

I don't know how to convert it to python typo like everyone did

quiet coral
slate swan
#

for example you could use guild.get_member(id)

#

member = yourGuildInstance.get_member(396607194910556162)

#

would be u

#

make sure to have members intent enabled

#

and guild can be ctx.guild... ig?

#

You don't need members intent for that

#

!d discord.Guild.get_member

unkempt canyonBOT
quiet coral
#
async def ping(ctx):
    guild=ctx.guild
    sido=guild.get_member('439800066312503297')
    await ctx.send(sido.mention)
#

cam you tell me what is wrong?

ripe jackal
#

and is there any error?

quiet coral
ripe jackal
#

i'm not really sure

#

i think you should take off the

#

''

quiet coral
crystal wind
#

How do we shortly delete the message after you do a command on python?

ripe jackal
placid skiff
unkempt canyonBOT
#

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

Sends a message to the destination with the content given.

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

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

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

As you can see the send method has a delete_after

#

It takes an int has argument which is the time in seconds after the message should be deleted

crystal wind
#

Doesn't it do to the bot's message?

#

I meant to me.

placid skiff
#

Well then you have to you use ctx.message.delete

crystal wind
#

that's it?

placid skiff
#

It deletes the message that invoked the command

#

If you want to delete it after a certain time you have to use asyncio

crystal wind
#

does it take an argument when you do ctx.message.delete?

placid skiff
#

!d discord.Message.delete

unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.

Changed in version 1.1: Added the new `delay` keyword-only parameter.
placid skiff
#

Oh so it had a delay lol, yes it takes delay which i think is the same as delete_after

crystal wind
kindred epoch
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

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

thats what ur gonna use

#

use the check to see if only that specific user votes

#

the thing i linked u also has examples

slate swan
#

im strugling with gerttting my cogs to lode

#

that was typed so badly

kindred epoch
#

and?

slate swan
#

They wont load, im new to using cogs so I have no clue what im doing

kindred epoch
#

does it send any errors?

slate swan
#

i have a try and except so it says cannot load

kindred epoch
#

send the error

slate swan
kindred epoch
#

the full error

slate swan
#

thats what it says

#

thats what i have it say

#

You have a custom error handler (try/except), remove it

kindred epoch
#

ok then remove the try except and then send the full error

slate swan
#
  File "main.py", line 604, in <module>
    bot.load_extension(extention)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: SyntaxError: invalid syntax (<fstring>, line 1)```
kindred epoch
#

send the whole code in cogs.event

slate swan
#
import discord
from discord.ext import commands
import datetime
from datetime import datetime
from replit import db
class Events(commands.Cog):
    def __init__(self, bot):
        self.now = datetime.now()
        self.current = self.now.strftime("%H:%M:%S")
        self.bot = bot
        self.color = 0x2f3136
    @commands.Cog.listener()
    async def on_guild_join(self, guild):
     db[f"{guild.id} welc"] = f"NEW GUILD"
     db[f"{guild.id} msg"] = f"`SET NEW MESSAGE`"
     db[f"{guild.id} footer"] = f"SET NEW FOOTER"
     db[f"{guild.id} welcome"] = "ENABLED"
     db[f"{guild.id} mod-logs"] = "CHANNEL.ID"
     print(f"{self.current}: Joined new guild")

    @commands.Cog.listener()
    async def on_member_ban(self, member):
        async for entry in member.guild.audit_logs(action=discord.AuditLogAction.ban):
            embed = discord.Embed(title="Vira",description=f"""**Suspicious Activity**
Action: **Ban**
Author: **{0.user}**
Banned: **{0.target}**
""",color=self.color)
            mod = db[f"{guild.id} mod-logs"]
            await mod.send(embed=embed)
    @commands.Cog.listener()
    async def on_member_join(self, member):
        t = db[f"{guild.id} welcome"]
        if t == "ENABLED":
            pass
        else:
            pass
            


         

    

def setup(bot):
    bot.add_cog(Events(bot))
#

How can I fix this?


te = {
            "🇦": "a",
            "🇧": "b",
            "🅱": "b",
            "🇨": "c",
            "🇩": "d",
            "🇪": "e",
            "🇫": "f",
            "🇬": "g",
            "🇭": "h",
            "🇮": "i",
            "🇯": "j",
            "🇰": "k",
            "🇱": "l",
            "🇲": "m",
            "🇳": "n",
            "🇴": "o",
            "🇵": "p",
            "🇶": "q",
            "🇷": "r",
            "🇸": "s",
            "🇹": "t",
            "🇺": "u",
            "🇻": "v",
            "🇼": "w",
            "🇽": "x",
            "🇾": "y",
            "🇿": "z"}```
#

Error: TypeError: can only concatenate str (not "dict") to str

kindred epoch
#

also, why are you importing datetime 2 times?

slate swan
#

ughh

#

everything i do never works

slate swan
flat solstice
#

Anyone know of a good lib which will allow me to proxy my bot as another bot? I saw d.py has some docs on it but I did some googling and found some slack and reddit threads saying that d.py's bot proxy system was broken due to a incompatibility with with aiohttp or something (it was a little while ago)

slate swan
#

hi, im currently trying to fix some old code that is broken currently and it's a leaderboard command..
the code is here:


@client.command(aliases = ["lb"])
async def leaderboard(ctx,x = 1):
    users = await get_bank_data()
    leader_board = {}
    total = []
    for user in users:
        print(user)
        name = int(user)
        total_amount = users[user]["wallet"]
        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)

and the error i get is discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: invalid literal for int() with base 10: "<member 'id' of 'User' objects>"
anyone know?

#
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: SyntaxError: invalid syntax (<fstring>, line 1)
``` how do i fix
#

im guessing i unload it

kindred epoch
#

id_ is a decimal so its raising that error

halcyon sparrow
#

How about you fix your import statements and instead of using the datetime in the init you do it somewhere else

slate swan
kindred epoch
slate swan
#

the code is not mine, its some old code im trying to revive

kindred epoch
slate swan
#

maybe that will help you

kindred epoch
#

make your own code

#

whats wrong with that?

slate swan
#

im trying to lewaren

slate swan
#

just i dont have the skills, plus this seems easier

#

and ill get a basic idea of how it works

halcyon sparrow
#

pithink I think it'll be easier to just go datetime.now() and store that

slate swan
#

ughh

placid skiff
# slate swan im trying to lewaren

If you just copy code from github you will not learning anything, you will finish up to don't understand nothing of what is written in the code

kindred epoch
#

lol

slate swan
slate swan
#

this just wont work so i came here

fervent canopy
#

fairs

kindred epoch
slate swan
placid skiff
slate swan
slate swan
slate swan
slate swan
kindred epoch
slate swan
#

Okay, it's a bad word blocking part if my bot though.

#

to convert text to emojis if seen when swearing

halcyon sparrow
#

And if you add bad words already in emojis where you're storing the text bad words

slate swan
#
@bot.command()
async def idk(ctx, user: discord.User = None):
  if user == None:
    print("your hot")

  profile = await user.profile()
  mutual_guilds = profile.mutual_guilds

how would i use this to create an invite link to all the mutual guilds then print all of the invites in console

slate swan
#

mutual guilds witht the bot and the user

#

that is mentioned

kindred epoch
#

why do you want to do that?

pliant gulch
#

Are you selfbotting?

slate swan
#

i wanna make my bot create an invite in all the mutual guilds then send them to me

slate swan
pliant gulch
#

profile() is only allowed for Non userbots

kindred epoch
#

and whatever yo're trying to do is called privacy breaching

pliant gulch
#

You can just skip profile() and do User.mutual_guilds

#

!d discord.User.mutual_guilds

unkempt canyonBOT
#

property mutual_guilds: List[Guild]```
The guilds that the user shares with the client.

Note

This will only return mutual guilds within the client’s internal cache.

New in version 1.7.
kindred epoch
#

creating invites to random servers

final iron
#

How would I make an embed field without a name?

slate swan
#

its not random

kindred epoch
#

name="\u200b"

slate swan
#

its invites to servers the user is in

#
import discord
from discord.ext import commands
import psutil

class Events(commands.Cog):
    def __init__(self, bot):
        self.now = datetime.now()
        self.current = self.now.strftime("%H:%M:%S")
        self.bot = bot
        self.color = 0x2f3136
    @commands.Cog.listener()
    async def on_guild_join(self, guild):
     db[f"{guild.id} welc"] = f"NEW GUILD"
     db[f"{guild.id} msg"] = f"`SET NEW MESSAGE`"
     db[f"{guild.id} footer"] = f"SET NEW FOOTER"
     db[f"{guild.id} welcome"] = "ENABLED"
     db[f"{guild.id} mod-logs"] = "CHANNEL.ID"
     print(f"{self.current}: Joined new guild")

    @commands.Cog.listener()
    async def on_member_ban(self, member):
        async for entry in member.guild.audit_logs(action=discord.AuditLogAction.ban):
            embed = discord.Embed(title="Vira",description=f"""**Suspicious Activity**
Action: **Ban**
Author: **{0.user}**
Banned: **{0.target}**
""",color=self.color)
            mod = db[f"{guild.id} mod-logs"]
            await mod.send(embed=embed)
    @commands.Cog.listener()
    async def on_member_join(self, member):
        t = db[f"{guild.id} welcome"]
        if t == "ENABLED":
            pass
        else:
            pass
            


         

    

def setup(bot):
    bot.add_cog(Events(bot))

#

line 1: invalid syntax

kindred epoch
pliant gulch
#

Not really random

halcyon sparrow
#

You have to indent after a :

pliant gulch
#

The bot would need to be in the server as well

slate swan
#

yes

pliant gulch
#

to be a mutual guild

slate swan
#

yeh

#

so back to the main question how can i use this to create an invite in all the mutual guilds

kindred epoch
pliant gulch
#

Which makes it not a random server

#

The only thing to worry about is if you have permission from the servers owner if you can make invites

#

as discord has said before that they don't like that

slate swan
#

yeh

#

im going to make it so the command only works if the server owner enables it

#

but anyways

#

thats besides the point

halcyon sparrow
#

Sorry I pasted wrong

#
import discord
from discord.ext import commands
import psutil

class Events(commands.Cog):
    """Description here."""
    
    def __init__(self, bot):
        """Initialize bot attributes."""
        self.now = datetime.now(),
        self.current = self.now.strftime("%H:%M:%S"),
        self.bot = bot,
        self.color = 0x2f3136
    
    @commands.Cog.listener()
    async def on_guild_join(self, guild):
        """Describe what this does.""""
        db[f"{guild.id} welc"] = f"
#

Compare your begging code to this. You indented two spaces instead of four. You might want to fix your editor. You're not adding doc strings as well and they are pretty important.

desert iris
#

btw you don't need the , after self.variable = value

kindred epoch
desert iris
#

liked in self.now = datetime.now(), you don't need the ,

kindred epoch
#

ig he just wanted it, does not really change anything if he does not have that

desert iris
#

yeah ik i was just saying

#

it still works fine both ways

kindred epoch
#

ye

halcyon sparrow
#

I think I fixed the whole indent thing

#
import discord
from discord.ext import commands
import psutil

class Events(commands.Cog):
    """Description here."""
    
    def __init__(self, bot):
        """Initialize bot attributes."""
        self.now = datetime.now(),
        self.current = self.now.strftime("%H:%M:%S"),
        self.bot = bot
    
    @commands.Cog.listener()
    async def on_guild_join(self, guild):
        """Describe what this does."""
        db[f"{guild.id} welc"] = f"UILD"
        db[f"{guild.id} msg"] = f"`SET NEW MESSAGE`"
        db[f"{guild.id} footer"] = f"SET NEW FOOTE"
        db[f"{guild.id} welcome"] = "ENABLED"
        db[f"{guild.id} mod-logs"] = "CHANNEL.ID"
        print(f"{self.current}: Joined new guild")
    
    @commands.Cog.listener()
    async def on_member_ban(self, member):
        """description"""
        async for entry in member.guild.audit_logs(action=discord.AuditLogAction.ban):
            ban_embed = discord.Embed(
                title="Vira",
                description=f"""
                    **Suspicious Activity**Action: **Ban**  
                    Author: **{0.user}**
                    Banned: **{0.target}**
                    """,
                color= 0x2f3136
            )
            mod = db[f"{guild.id} mod-logs"]
            await mod.send(embed=ban_embed)
    
    @commands.Cog.listener()
    async def on_member_join(self, member):
        """Desc"""
        t = db[f"{guild.id} welcome"]
        if t == "ENABLED":
            pass
        else:
            pass


def setup(bot):
    bot.add_cog(Events(bot))
hasty iron
#

they’re all trash

hasty iron
#

yes there aren’t, forks that is

#

i don’t know how good other libs are

halcyon sparrow
#

Hikari is one

steel trench
#

I mean, the disgord library (go) is good but that’s not python lole

#

I can’t think of any other python ones to recommend

slate swan
#
import discord
from discord.ext import commands
from replit import db
import datetime
from datetime import datetime
from discord_components import DiscordComponents, Button, ButtonStyle, Select, SelectOption

class Welcome(commands.Cog):
    def __init__(self, bot):
        color = 0x2f3136
        now = datetime.now()
        current = now.strftime("%H:%M:%S")
        self.bot = bot
        check = "![b_yes](https://cdn.discordapp.com/emojis/892932723528835162.webp?size=128 "b_yes")"
    @commands.command()
    async def welchan(self, ctx, channel: discord.TextChannel):
        j = db[f"{ctx.guild.id} welc"]
        if channel is None:
            await ctx.send(f"{ctx.author.mention} please mention a channel, or provide a channel name/id")
        if j == "NEW GUILD":
            del db[f"{ctx.guild.id} welc"]
            db[f"{ctx.guild.id} welc"] = channel.id
            embed = discord.Embed(title="Vira",description=f"""{self.check} Welcome Channel Set
Channel: **{channel.mention}**""")
            await ctx.send(embed=embed)
            
            
            

            

def setup(bot):
    bot.add_cog(Welcome(bot))    

#

the cmd wont work, any idea why

hasty iron
#

why are you using replit db

steel trench
slate swan
hasty iron
#

and that doesn’t answer my question

slate swan
#

my question wasnt answered either

hasty iron
#

okay

#

so you expect us to just know what’s wrong? no error no nothing?

slate swan
#

nope, the command just doesn't work

hasty iron
#

"just doesn’t work" isnt valid

#

are you loading the cog

slate swan
#

yes

#

not

hasty iron
#

check is not an attribute

slate swan
hasty iron
#

??

slate swan
#

ohh i get what your saying

hasty iron
#

ok, so why are you using replit db

vague grove
#

how can I have a command like @client.command(), but have the bot respond to a word

#

as a command

slate swan
#

not as bad as y'all think

#

but

hasty iron
#

hahah sure man

#

not as bad yeah

slate swan
#

but have you used it??

hasty iron
#

it’s practically json

slate swan
#

it works tho right ??

pliant gulch
#

Pretty sure at this point that repl.it's "database" is just a dictionary they made not ephemeral

pliant gulch
#

checks out to me

slate swan
#

how do i get the current time

bright palm
#
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2021, 10, 5, 12, 1, 21, 352909)
slate swan
#

fixed

#

im jsut dumb

static topaz
#

I'm trying to pass a printed function from terminal to discord using my bot, how would this be done? at the moment I'm getting a message in discord that says function results at memory address

#

still very new to python

slate swan
#
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.help' raised an error: TypeError: __init__() missing 1 required positional argument: 'func'
#

what does this mean

hasty iron
#

you aren’t passing an argument which you are supposed to pass to the init

valid perch
#

And it looks like it needs another arg

static topaz
# valid perch Code?

got that bit working now, however discord doesn't seem to like ascii tables, so now trying to figure out how to pass the data from an sqlite query into embeds

slate swan
# slate swan ```py raise errors.ExtensionFailed(key, e) from e discord.ext.commands.errors.Ex...
import discord
from discord.ext import commands

class Help(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    @commands.Command()
    async def help(self, ctx):
        embed = discord.Embed(title="Vira", color=0x2f3136)
        embed.add_field(name=f"**Moderation**",value=f"`ban`, `kick`, `nuke`, `role`, `roleall`, `guildname`, `modlogs`")
        embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/889013207849635843/892952355698540544/image0.png")
        await ctx.send(embed=embed)


def setup(bot):
    bot.add_cog(Help(bot))
#

fixed

#

the capital c in Command fuucked it uo

tulip oracle
#

member intents exist

#

intents = discord.Intents.all()

#

in your bot constructor line

boreal osprey
#

i got this after trying something new with my avatar command and adding a if statement

boreal osprey
# boreal ravine code?
@bot.command(aliases = ['av'])
async def avatar(ctx, *, member : discord.Member=Member):
    
    if member == None:
        member = ctx.author
        
    emb=discord.Embed(title = f"{member.name}'s avatar", color = discord.Colour.random())
    emb.set_image(url=member.avatar_url)
    await ctx.send(embed=emb)
slate phoenix
#

change the async def avatar(ctx, *, member : discord.Member=Member): to async def avatar(ctx, member : discord.Member=None):

boreal ravine
#

why do u need * tho

boreal osprey
#

idk why, i though i did for some reason

slate phoenix
#

yeah its not necessary

boreal osprey
#

anyways it work now

boreal ravine
#

👍

somber musk
#

this might seem like a dum question to ask but if i add a music bot to a server and someone reports it for idk breaking tos or smthn will the server be deleted or the bot

steel trench
#

Can't see why discord would delete the server over that

kindred epoch
steel trench
#

But discord devs have been wonky in the past, so don't quote me on that.

slate phoenix
#

im p sure youtube has to deal with that not discord and the server wouldnt be deleted

boreal ravine
#

honestly discord wont bother removing small discord bots but your still breaking the tos

somber musk
boreal ravine
#

yes

somber musk
#

becuz a mod is refraining to adding since he thinks its gonna delete the server if reported

slate phoenix
#

the server wouldnt get deleted

somber musk
#

for sure?

slate phoenix
#

i see no reason why

#

The server isnt breaking the rules the bots owner is

somber musk
#

mhm

#

leme ss this

slate phoenix
#

But at most youtube would send a c&d to the bots owner

#

they arent going for small bots though

somber musk
boreal ravine
#

cease

#

and decease order

slate phoenix
#

cease and desist in short it means "piss off and we wont sue you"

boreal ravine
#

lol

somber musk
slate phoenix
#

the server will be fine

#

the bot may not be

#

but i doubt yt cares about a bot in 5000 servers

somber musk
#

i really dont care abt the bot i can just make a new bot if it gets deleted for my own use with the same code different token

slate swan
#

is on_guild_join valid?

slate phoenix
#

!d discord.on_guild_join

unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.

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

yes

pliant gulch
somber musk
pliant gulch
#

You know how labels are they are quite stingey I wouldn't be surprised

#

Not after groovy and rhythm shutdown

slate swan
#

what about activity=discord.Watching?

slate phoenix
#

its discord.ActivityType.watching

pliant gulch
slate swan
#

and how can i get a full list of members? currently i have {len(bot.members)} but thats invalid

slate phoenix
#

bot.users

quick sierra
#

Does anyone have a "main.py"? I am young '-'

slate swan
slate phoenix
#

well if you're trying to change the presence its activity=discord.Activity(type=discord.ActivityType.watching)

slate swan
slate phoenix
#

that means you dont have intents enabled

#

!intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

weird, it showed how many servers it was in when i used bot.guilds

slate phoenix
#

because guild intents are enabled by default

#

members intents arent

slate swan
#

ahh

#

ill check that out, thanks

slate phoenix
#

np

visual island
#
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('discord')
logger.setLevel(logging.INFO)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

```are there anything I can do to simplify this?
#

It's looking realllyy messy rn

slate swan
#

is there a way to use requests to send an embed

slate swan
lusty haven
#

!d discord.User

slate swan
#

!d discord.User

unkempt canyonBOT
#

class discord.User```
Represents a Discord user.

x == y Checks if two users are equal.

x != y Checks if two users are not equal.

hash(x) Return the user’s hash.

str(x) Returns the user’s name with discriminator.
slate swan
lusty haven
#

what?

slate swan
#

the embed you were looking for

lusty haven
#

oh ok

slate swan
lusty haven
#

why doesn't it tell me about the properties?

slate swan
#

go into the docs for more abt it

lusty haven
#

yeah I did.

#

bye!

blazing vapor
#

how do i fix this error Command raised an exception: TypeError: 'Int64' object is not subscriptable

my code is ```py
@commands.command()
async def buy(self,ctx,item_name,amount = 1):
data = loadf('databases/shop1.json')
item_name = item_name.lower()
name_ = None
for item in data["content"]:
print(data)
print(item)
name = item['id'].lower()
if name == item_name:
name_ = name
price = item['price']
buyer_money = user_balance.find_one({'_id': ctx.author.id})

    buyer_cash = buyer_money['balance']['cash']
    if price > buyer_cash['balance']['cash']:
        await ctx.send('You Don\'t Even Have That Much Money Idiot 😛')
        return
    else:
        user_balance.update_one(buyer_cash, {"$inc": {
                'balance.cash': -price}})
        user_inventory.insert_one({'_id': ctx.author.id, 'items': {
        name_: amount
        }})
        await ctx.send(f'You have successfully bought {amount} {name_}')```
maiden fable
#

And in which line u getting the error?

blazing vapor
maiden fable
#

Ah cool

blazing vapor
maiden fable
#

And what's printed when u print item?

zenith flicker
#

load is json.load right?

maiden fable
blazing vapor
maiden fable
blazing vapor
# maiden fable Seems like item is an int
{
  "content":  [
    {
      "id": "cookie",
      "name": "Cookie",
      "emoji": ":cookie:",
      "price": 100,
      "rarity": 1.0
    },
    {
      "id": "apple",
      "name": "Apple",
      "emoji": ":apple:",
      "price": 50,
      "rarity": 1.0
    },
    {
      "id": "banana",
      "name": "Banana",
      "emoji": ":banana:",
      "price": 60,
      "rarity": 0.5
    }
  ]
}```
#

here is my shop json

blazing vapor
maiden fable
#

Mhm

zenith flicker
blazing vapor
#

i really really wanna make my buy command work 🥺

blazing vapor
maiden fable
zenith flicker
#

oh sorry

maiden fable
lilac latch
#

How to set 2 pics in an embed??

zenith flicker
#

yeah you gotta do data["content"][item]["price"]

blazing vapor
#

ye lemme try

lilac latch
zenith flicker
#

discord only lets you have 1

lilac latch
zenith flicker
#

you can use the thumbnail as a second image though

lilac latch
#

This sucks

zenith flicker
#

idk thats just how it is

lilac latch
blazing vapor
zenith flicker
#

weird

#

try data[item]...

blazing vapor
#

wdym>

#

im sorry im a bit dumb

zenith flicker
#

data[item]['price']

maiden fable
#

Works?

boreal ravine
blazing vapor
zenith flicker
#

wdym

blazing vapor
#

if item_name == item['id'].lower()

#

will this work?

zenith flicker
#

oh i see

zenith flicker
#

if not, try enumerating the list like this ```py
for item_pos, item in enumerate(data['content']):
if item_name == data['content'][item_pos]['id'].lower():

maiden fable
#

Yea this should work

blazing vapor
#

thanks guys it fixed it but there is another error

#

TypeError: 'Int64' object is not subscriptable

maiden fable
#

Which line

somber musk
#

Guys
Is dank memer
Coded by
100s of people?

blazing vapor
maiden fable
blazing vapor
maiden fable
boreal ravine
#

Whats the difference between guild.get_role() and discord.utils.get()

maiden fable
maiden fable
maiden fable
maiden fable
blazing vapor
boreal ravine
#

python classes hurt my brain

maiden fable
boreal ravine
blazing vapor
maiden fable
maiden fable
maiden fable
blazing vapor