How do I display the model menu via the button? - python

I want to output the modal menu through the button and embed, but it gives an error that disnake did not understand the lable of the button, tell me how to fix and output the menu through the button. I also want to know how to add reactions to the embed something like voting. I tried to do it but it gives an error.
import disnake
from disnake.ext import commands
from disnake import TextInputStyle, Button, ButtonStyle, ActionRow
from config import settings
bot = commands.Bot(command_prefix="!", intents= disnake.Intents.all(), activity=
disnake.Game('game',))
bot.remove_command('help')
#bot.event
async def on_ready():
print(f'Вы вошли как {bot.user}')
#bot.command()
#commands.has_role(IDROLE)
async def support(ctx):
emb = disnake.Embed(color = 0x71368a, title = 'title',
description =
f"""
**description**
""",
colour = 0x71368a
)
rowA = ActionRow(
Button(style = ButtonStyle.green, label = 'button', emoji = '🛠', custom_id =
'button_button')
)
await ctx.send(embed = emb, components = [rowA])
#bot.event
async def on_button_click(inter):
class MyModal(disnake.ui.Modal):
def __init__(self):
components = [
disnake.ui.TextInput(
label="ЧЕГО БУДЕТ КОСАТЬСЯ ВАШЕ ПРЕДЛОЖЕНИЕ?",
placeholder="Сервер, бот, игра.",
custom_id="ЧЕГО БУДЕТ КОСАТЬСЯ ВАШЕ ПРЕДЛОЖЕНИЕ?",
style=TextInputStyle.short,
min_length=3,
max_length=50,
),
disnake.ui.TextInput(
label="ОПИШИТЕ ВАШЕ ПРЕДЛОЖЕНИЕ",
placeholder="Wow",
custom_id="Описание",
style=TextInputStyle.short,
max_length=2000,
),
disnake.ui.TextInput(
label="ЧЕМ ВАШЕ ПРЕДЛОЖЕНИЕ БУДЕТ ПОЛЕЗНО ИГРОКАМ",
placeholder="wow",
custom_id="Чем идея будет полезна",
style=TextInputStyle.short,
max_length=2000,
),
]
super().__init__(
title="Новое предложение",
custom_id="create_tag",
components=components,
)
async def callback(self, inter: disnake.ModalInteraction):
embed = disnake.Embed(title="```Спасибо за предложение!```", color =0x00FF9A )
embed.set_author(name = f"{inter.author.name}" ,icon_url= f"{inter.author.avatar}")
for key, value in inter.text_values.items():
embed.add_field(
name=key.capitalize(),
value=value[:1024],
inline=False,
)
await inter.response.send_message(embed=embed)
#bot.event
async def on_member_join(member):
role = member.guild.get_role(IDROLE)
await member.add_roles(role)
bot.run(settings['TOKEN'])
ERROR:
ImportError: cannot import name 'InvalidArgument' from 'discord' (C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_init_.py)

Related

Slash command with options to cog

I made a slash command that echoes a message. But I wanted to separate it from the main.py, and I couldn't do it. I made many commands to cogs before, but none was a Slash Command.
I used the #client.command under:
class echo(commands.Cog):
def __init__(self, client):
self.client = client
#client.command
#the rest of the code
...
I got an error message saying, "interactions.option isn't recognized". I created 3 options (1 required and the rest are optional):
#client.command(name="echo",description="testing", default_member_permissions=interactions.Permissions.ADMINISTRATOR,
options=[
interactions.Option(
name = "text",
required = True,
description = "text",
type = interactions.OptionType.STRING
),
interactions.Option(
name = "channel",
required = False,
description = "channel",
type = interactions.OptionType.CHANNEL
),
interactions.Option(
name = "timer",
required = False,
description = "timer in minutes(e.g. 20, 120)",
type = interactions.OptionType.INTEGER
)])
I've tried finding an alternative, but couldn't make it.
Also, I had an error saying that there was something about ADMINISTRATOR so I made it lowercase. all of these and more work just fine on my main bot file.
here is my whole code in the main file:
import discord, asyncio, interactions
intents = discord.Intents.all()
client = interactions.Client(token="MY TOKEN")
#client.event
async def on_ready():
print("\nBot is awake!\n")
#client.command(name="echo",description="testing", default_member_permissions=interactions.Permissions.ADMINISTRATOR,
options=[
interactions.Option(
name = "text",
required = True,
description = "text",
type = interactions.OptionType.STRING
),
interactions.Option(
name = "channel",
required = False,
description = "channel",
type = interactions.OptionType.CHANNEL
),
interactions.Option(
name = "timer",
required = False,
description = "timer in minutes(e.g. 20, 120)",
type = interactions.OptionType.INTEGER
)])
async def echo(ctx: interactions.CommandContext, text: str, channel: str = None, timer: int = None):
if channel is None and timer is None:
await ctx.send(text)
elif channel is not None and timer is None:
await channel.send(text)
await ctx.send(f"I sent your message to {channel.mention}")
elif channel is None and timer is not None:
await ctx.send(f"I will send your message after {timer} minutes.")
await asyncio.sleep(timer * 60)
await ctx.send(text)
elif channel is not None and timer is not None:
await ctx.send(f"I will send your message in {channel.mention} after {timer}")
await asyncio.sleep(timer * 60)
await channel.send(text)
client.start()

How to delete take certain channels and categories and delete them? (Discord.py)

I want that when a user writes a command, the bot deletes certain channels with certain names, but I can't succeed.
Error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'get_category'
Code:
#client.command()
async def verification_channels_delete(ctx):
await ctx.send('Удаляю категории и каналы для верефикации...')
category1 = await ctx.message.guild.get_category('Verification')
category2 = await ctx.message.guild.get_category("Chat")
await category1.delete()
await category2.delete()
channel1 = await ctx.message.guild.get_text_channel("Verification")
channel2 = await ctx.message.guild.get_text_channel("Chat")
await channel1.delete()
await channel2.delete()
await ctx.send('Я удалил все каналы для верефикации!')
If you want to get channel, category, or anything else by name you should use discord_utils for it:
from discord.utils import get
#client.command()
async def verification_channels_delete(ctx):
category1 = get(ctx.guild.categories, name = "Verification")
category2 = get(ctx.guild.categories, name = "Chat")
await category1.delete()
await category2.delete()
channel1 = get(ctx.guild.text_channels, name = "verification")
channel2 = get(ctx.guild.text_channels, name = "chat")
await channel1.delete()
await channel2.delete()

How can I get a random image from image search using a command discord.py

I know I can make a command like:
async def cat(self, ctx):
response = requests.get('https://aws.random.cat/meow')
data = response.json()
embed = discord.Embed(
title = 'Kitty Cat 🐈',
description = 'Cat',
colour = discord.Colour.purple()
)
embed.set_image(url=data['file'])
embed.set_footer(text="")
await ctx.send(embed=embed)
not my code btw
But how do I make a command to search like !image computer and it gets a random computer image from image search and sends it to the channel
You can use the Unsplash Source API, as suggested by Bagle.
#command(name = "img")
async def cat(self, ctx, arg):
embed = discord.Embed(
title = 'Random Image 🐈',
description = 'Random',
colour = discord.Colour.purple()
)
embed.set_image(url='https://source.unsplash.com/1600x900/?{}'.format(arg))
embed.set_footer(text="")
await ctx.send(embed=embed)
And execute the command with
{bot_prefix}img computers

Discord webhook with embed

I made a few commands for my discord bot. When I Send the command .y or .j6 for the 2nd time it pushes the first one with the second. How can I fix this?
(I need to post more details but i dont have them so i write this so i can post this so dont read this because this is trash)
import discord
from discord.ext import commands
from discord_webhook import DiscordWebhook, DiscordEmbed
async def on_ready():
print('Bot is ready.')
client = commands.Bot(command_prefix= '.')
webhook_urls = ['https://discordapp.com/api/webhooks/694265463936647289/zwRbi6A_jHp9r7kbTwOlWir9rS3-cXtMa6XLHHmrzwgyJtQaLPiisbSQBRgq7v39F6MG', 'https://discordapp.com/api/webhooks/699705671440138291/52awf2UE2TgVhumFQKp8ZOo-lz4iBtjt786NC1W1TDElAKCx4spXLP3RNi7O4avuQpHo']
webhook = DiscordWebhook(url=webhook_urls)
#client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
#client.command()
async def raffle(ctx, link, store, sneaker, raffletype ):
channel = client.get_channel(642837709198721034)
embed = discord.Embed(
title=sneaker,
description=store,
url=link,
colour=discord.Colour.blue()
)
embed.add_field(name="Release type", value=raffletype)
embed.set_footer(text='The Hypesply | Chip#4600')
await channel.send(embed=embed)
#client.command()
#commands.has_role('Owner')
async def j6(ctx, link, store, raffletype ):
embed = DiscordEmbed(
title="Nike AirJordan 6 'DMP'",
url=link,
colour=discord.Colour.blue()
)
embed.add_embed_field(name="Store", value=store)
embed.add_embed_field(name="Release type", value=raffletype)
embed.set_thumbnail(url="https://static.sneakerjagers.com/products/660x660/126329.jpg")
embed.set_footer(text='The Hypesply | Chip#4600')
webhook.add_embed(embed)
webhook.execute()
#client.command()
#commands.has_role('Owner')
async def y(ctx, link, store, raffletype):
embed = DiscordEmbed(
title="Adidas Yeezyboost 350 V2 'Linen'",
url=link,
colour=discord.Colour.blue()
)
embed.add_embed_field(name="Store", value=store)
embed.add_embed_field(name="Release type", value=raffletype)
embed.set_thumbnail(url="https://static.sneakerjagers.com/products/660x660/155433.jpg")
embed.set_footer(text='The Hypesply | Chip#4600')
webhook.add_embed(embed)
webhook.execute()```

Discord python bot problem with giveng role

I have got an error: TypeError: on_message() missing 1 required positional argument: 'member'
How do I fix this error and what do I have to do with it?
Here is my code:
import discord
import config
client = discord.Client()
#client.event
async def on_message(message, member):
id = client.get_guild(config.ID) # ID в файле config
channels = [
647074685535649802,
636901028478058497,
690272147050070158,
694196995887202375,
690276595578962177,
654662320735387648,
650381379892412426,
641704849196711976,
]
badwords = ["лузер", "расизм", "нацизм"]
valid_users = ["Resadesker#1103"]
unwarnusers = ["ResadeskerBOT#7104"]
if str(message.author) in valid_users:
for channelo in channels:
if message.content[:message.content.find(' ')] == "$spam":
channel = client.get_channel(channelo)
await channel.send(message.content[message.content.find(' '):])
for word in badwords:
if word in message.content.lower():
if str(message.author) != "ResadeskerBOT#7104":
warnFile = open("D:/python/disbot/warns.txt", "a")
warnFile.write(str(message.author) + "\n")
warnFile.close()
mutedRole = discord.utils.get(message.guild.roles, name='JB-MUTED')
await member.add_roles(mutedRole)
channel = client.get_channel(696315924591935488)
await channel.send(f"--------------------\nЗа человеком {message.author.mention} было замечено нарушение. \nВот его сообщение: \n{message.content} \nНарушение было в канале {message.channel}\n--------------------")
client.run(config.TOKEN)
You are using old code from before the discord.py rewrite but running a newer version.
Just change your:
#client.event
async def on_message(message, member):
to
#client.event
async def on_message(message):
And it should work.

Categories

Resources