How i can ad a user a single role with a button - python

Hi i want for my comment which will send 3 embeds and an Button when you click on the Button that you get the role "weeb"
(btw im starting bot coding im not a pro and i understand only the basics even when you can call these "basics")
btw the string text is german because it will be for a german server
The class with the Button:
import discord
from discord import ComponentInteraction
from discord.ext import commands
class RuleAcceptButton(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.on_click(custom_id='rule-accept-btn')
async def button1(self, ctx: ComponentInteraction, _):
role_id = 1046854949373489203
def setup(bot):
bot.add_cog(RuleAcceptButton(bot))
The class with the setup command:
#commands.Cog.slash_command(base_name='setup', name='rules', description='Send a Embed of the Rules')
async def setup_rules(self, ctx):
embed_rules_1 = discord.Embed(description='sample text'
embed_rules_1.set_author(name='§1 – Allgemeine Regeln')
embed_rules_1.set_thumbnail(url='https://i.pinimg.com/originals/93/f0/00/93f0006c2d5da2f25de2951fb3f994bf.jpg')
embed_rules_2 = discord.Embed(colour=16711680, description='sample text'
# ab hier Embed2
embed_rules_2.set_author(name='§2 – Zusätzliche Regeln für Voice-Chats/Voice-Channels')
embed_rules_2.set_thumbnail(url='https://i.pinimg.com/originals/93/f0/00/93f0006c2d5da2f25de2951fb3f994bf.jpg')
# ab hier Embed3
embed_rules_3 = discord.Embed(colour=16711680, description='sample text'
embed_rules_3.set_author(name='§3 – Zusätzliche Regeln für den Chat.')
embed_rules_3.set_thumbnail(url='https://i.pinimg.com/originals/93/f0/00/93f0006c2d5da2f25de2951fb3f994bf.jpg')
await ctx.respond(embed=embed_rules_1)
await ctx.respond(embed=embed_rules_2)
await ctx.respond(embed=embed_rules_3, components=[
discord.Button(label='Accept Rules', custom_id='rule-accept-btn',style=discord.ButtonStyle.green)
i simply searched the whole internet and i didnt found anything

Related

Making a Telegram bot with Python with the `telebot` library

I'm trying to make a telegram bot with python but when I import telebot library (I have installed pyTelegramBotAPI & telebot libraries), but some parts don't work, like message_handler(), .reply_to() and .infinity_polling().
What could be causing this problem?
import telebot
import constant
from datetime import datetime
BOT_TOKEN = constant.api_key
bot = telebot.TeleBot(BOT_TOKEN)
#bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message, "Howdy, how are you doing?")
#bot.message_handler(commands=['help'])
def send_welcome(message):
bot.reply_to(message, "you can ask me datetime and hi to me and ask who am i and how am i")
#bot.message_handler(func=lambda message: True)
def javab(in_text):
user_mess = str(in_text).lower()
if user_mess in ('hi','hello','sup'):
bot.reply_to(user_mess, "hi bro wtf do u want")
if user_mess in ('time','what time is it?','time?'):
now = datetime.now()
date_time = now.strftime("%d/%m/%Y,%H:%M:%S")
bot.reply_to(user_mess, str(date_time))
if user_mess in ('who are u','who are you?','you?'):
bot.reply_to(user_mess, 'non of your business , im hironside')
if user_mess in ('how are u?','how are you?'):
bot.reply_to(user_mess, 'im good')
if user_mess in ('/stop'):
return 'ok good bye'
else:
bot.reply_to(user_mess, 'go fly a kite')
print('bot is runnig ......')
bot.infinity_polling(5)

Discord.py Button responses interaction failed after 3 min

The button doesn't respond if no one has clicked it in 3 minutes.
I saw that it was something with timeout but I don't know where to place it.
My code:
#Tickets
class Menu(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
#discord.ui.button(label="📥 Ticket", style=discord.ButtonStyle.grey)
async def menu1(self, interaction: discord.Interaction, button: discord.ui.Button):
with open("open_channels_user_id.json", "r") as f:
data = json.load(f)
user_id = data["user_id"]
if user_id != interaction.user.id:
admin_role = discord.utils.get(interaction.guild.roles, name="hulpje")
category = discord.utils.get(interaction.guild.categories, name='Ticket')
overwrites = {interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
interaction.guild.me: discord.PermissionOverwrite(read_messages=True),
interaction.user: discord.PermissionOverwrite(read_messages=True),
admin_role: discord.PermissionOverwrite(read_messages=True)}
new_ticket = await interaction.guild.create_text_channel(f'Ticket- {interaction.user.name}', category=category, overwrites=overwrites)
channel = client.get_channel(new_ticket.id)
embed = discord.Embed(title=f'Ticket- {interaction.user.name}', description="Goed dat je een ticket opent. \n Stuur alvast wat informatie zodat het makkelijker is voor het staff team.", color=0x004BFF)
await channel.send(embed=embed)
await interaction.response.send_message(f"Ticket is geopen met de naam: Ticket- {interaction.user.name}")
data['user_id'] = interaction.user.id
with open("open_channels_user_id.json", "w") as f:
json.dump(data, f)
time.sleep(3)
await interaction.channel.purge(limit=1)
else:
await interaction.channel.send("Je hebt al een ticket openstaan.")
time.sleep(5)
await interaction.channel.purge(limit=1)
async def menu(ctx):
view = Menu()
embed = discord.Embed(title="Ticket", description="Vragen, klachten of iets anders maak hier je Ticket aan en wordt zo snel mogelijk geholpen!", color=0x004BFF)
await ctx.send(embed=embed, view=view)
I don't know what to do. Pls help!
You can set the timeout value like this:
class Menu(discord.ui.View):
def __init__(self):
super().__init__(timeout=180) # Timeout value in seconds
self.value = None
If you set it to None, it will never time out, until you restart your bot.
If you want the view to persist between bot restarts, see this example here: https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py

How do I display the model menu via the button?

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)

Replit web server doesn't answer to Discord command

I would appreciate if anyone out there could help me.
I wanted to code a bot for a esports team, which does have a ticket included, on pycharm on my computer actually everything works fine, but when i then want to host it on replit it doesnt work. I have made the ticket with discord-components and as the button is clicked, the bot thinks, but does never send the messege and goes on with the code. But on my other replit file I have another ticket, but that does work just fine.
Does someone have an idea what could have gone wrong?
#client.command()
async def tryout(ctx):
server = client.get_guild(879321194506121247)
tryouter = get(server.roles, name="Tryouter")
embed_tryout = discord.Embed(title="Tryout",
description="*Start your tryout right now, to join HOC-Esports and start your clash royale esports journey*",
color=discord.Color.from_rgb(244, 246, 246))
embed_tryout.add_field(name="What we offer:",
value="• 4-5 scrims per week\n• A good organised team with engaged managers\n• Custom HOC logo + banner",
inline=False)
embed_tryout.add_field(name="What we demand from you:",
value="• You are engaged to improve yourself\n• You aren't toxic",
inline=False)
embed_tryout.add_field(name="Informations to the tryout""Infos zum Tryout",
value=f"You will make a bo5 against a {tryouter.mention}, who will rate your skill decide if you fit in our team or not",
inline=False)
await ctx.send(embed=embed_tryout, components=[
[Button(label="🎫 start tryout", style=1, custom_id="button1")]
])
#client.event
async def on_button_click(interaction):
if interaction.custom_id == "button1":
pass
else:
return
guild = interaction.guild
tryouter = get(guild.roles, name="Tryouter")
category = client.get_channel(997078909071929434)
await interaction.send(content="You just started a tryout", ephemeral=True)
benutzer = str(interaction.user)
user_letters = len(benutzer)
username = benutzer[:user_letters - 4]
ticket_channel = await guild.create_text_channel(name=f"Tryout of {username}", category=category)
user = interaction.author
tryoutrole = get(guild.roles, name= "Tryout")
visitorrole = get(guild.roles, name="Besucher")
esports_role = get(guild.roles, id=917100410400014426)
await user.add_roles(tryoutrole)
await user.remove_roles(besucherrolle)
await ticket_channel.set_permissions(user, view_channel=True, read_message_history=True, read_messages=True,
add_reactions=True, embed_links=True, attach_files=True,
use_external_emojis=True)
await ticket_channel.send(
f"Welcome {interaction.user.mention}. You just started a tryout.\nA {tryouter.mention} will take care of you.\nPlease send meanwhile your friendlink and your profile right here\nIf you don't want to make the tryout anymore, just close the ticket.",
components=[
Button(label="🔒 close ticket", style=2, custom_id="button2")
])
interaction2 = await client.wait_for("button_click", check=lambda i: i.custom_id == "button2")
await interaction2.send(content="You just closed the ticket", ephemeral=True)
time.sleep(5)
await ticket_channel.delete()
await user.remove_roles(tryoutrole)
if esports_role in user.roles:
return
await user.add_roles(visiterrole)

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()```

Categories

Resources