unofficial library for discord components(on development)

Overview

discord.py-buttons

Build Status PyPI version Documentation Status

unofficial library for discord buttons(on development)

Install

pip install --upgrade discord_buttons

Example

from discord import Client
from discord_buttons import DiscordButton, Button, ButtonStyle, InteractionType

bot = Client()
ddb = DiscordButton(bot)

@bot.event
async def on_message(msg):
    m = await msg.channel.send(
        "Content",
        buttons=[
            Button(style=ButtonStyle.blue, label="Blue"),
            Button(style=ButtonStyle.red, label="Red"),
            Button(style=ButtonStyle.URL, label="url", url="https://example.org"),
        ],
    )

    res = await ddb.wait_for_button_click(m)
    await res.respond(
        type=InteractionType.ChannelMessageWithSource,
        content=f'{res.button.label} clicked'
    )


bot.run("token")

Docs

The docs can contain lot of spelling mistakes, grammar errors so if there is a problem please create an issue!

Features

  • Send, Edit button messages
  • Get button click event!
  • Supports discord.ext.commands

Helps

  • Minibox - Button API explanation
  • Lapis - Told me how to replace a property
Comments
  • [Bug] Very high message roundtrip ping when the lib is loaded.

    [Bug] Very high message roundtrip ping when the lib is loaded.

    Bug Line

    I don't know where is the actual bug. My bot is over 8000 servers.

    image After a bot restart with the Cog unloaded the bot works fine. When I load the Cog it slows down.

    Excpected Action

    Just work

    Actual Action

    Well it works but slows down the bot.

    Reproducing the action

    Module loaded in a Cog:

        def __init__(self, client):
            self.client = client
            self.connection = client.dbconnection
            if not hasattr(client, "component_client"):
                self.component_client = DiscordComponents(client)
            else:
                self.component_client = client.component_client
    

    Also it is present in my on_ready() function as well. The cog loads when the bot is ready.

    Possible Solution

    I didn't manage to find anything.

    Environment

    • Python v3.8.5-final
    • discord.py v1.7.2-final
    • aiohttp v3.6.2
    • system info: Linux 5.4.0-73-generic #82-Ubuntu SMP Wed Apr 14 17:39:42 UTC 2021 Latest version of the lib from GitHub.

    Check

    • [x] Are you using the newest version?
    • [ ] Is this bug related to security issues?
    bug 
    opened by FightMan01 21
  • [Bug] Error when adding component to message

    [Bug] Error when adding component to message

    Bug Line

    Ignoring exception in command button:
    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 29, in button
        await ctx.send("Buttons!", components=[Button(label="Button", custom_id="button1")])
      File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/dpy_overrides.py", line 323, in send_override
        return await send(channel, *args, **kwargs)
      File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/dpy_overrides.py", line 300, in send
        data = await state.http.send_message(
      File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 156, in request
        kwargs['data'] = utils.to_json(kwargs.pop('json'))
      File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/utils.py", line 328, in to_json
        return json.dumps(obj, separators=(',', ':'), ensure_ascii=True)
      File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps
        return cls(
      File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
        chunks = self.iterencode(o, _one_shot=True)
      File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
        return _iterencode(o, 0)
      File "/usr/lib/python3.8/json/encoder.py", line 179, in default
        raise TypeError(f'Object of type {o.__class__.__name__} '
    TypeError: Object of type Button is not JSON serializable
    
    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: TypeError: Object of type Button is not JSON serializable
    

    Expected Action

    What did you expect the module to do? Send a message with a button when the button command is executed

    Actual Action

    What actually happened? It throwed an discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Object of type Button is not JSON serializable exception

    Reproducing the action

    How could you reproduce the action?

    from discord_components import DiscordComponents,InteractionEventType,ComponentsBot,Button
    
    TOKEN="bot token"
    
    client=ComponentsBot(command_prefix="?",help_command=None)
    
    @client.event
    async def on_ready():
        print("ready")
    
    @client.command()
    async def button(ctx):
        await ctx.send("Buttons!", components=[Button(label="Button", custom_id="button1")])
        interaction = await client.wait_for(
            "button_click", check=lambda inter: inter.custom_id == "button1"
        )
        await interaction.send(content="Button Clicked")
        
    client.run(TOKEN)
    

    Possible Solution

    How do you think you can fix this bug? Make the button class JSON serializable.

    Environment

    What is the version of the python? python 3.8.3

    Check

    • [x] Are you using the newest version?
    • [ ] Is this bug related to security issues?
    bug 
    opened by Markos-Th09 10
  • [Bug] Button Command within cogs

    [Bug] Button Command within cogs

    Hello, i now sucessfully made buttons working in the mainfile. now im trying to get it into cogs and used a examplecode in the examplefolder on this githubpage. However i get a dumb issure. I will provide the code im using and the error that appears when running the command below:

    Ignoring exception in on_socket_response
    Traceback (most recent call last):
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord\client.py", line 343, in _run_event
        await coro(*args, **kwargs)
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord_components\client.py", line 79, in on_socket_response
        event = self._events.get(res["d"]["data"]["component_type"], None)
    KeyError: 'component_type'
    An exception has occurred while executing command `button`:
    Traceback (most recent call last):
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord_slash\client.py", line 744, in invoke_command
        await coro
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord_slash\model.py", line 227, in invoke
        return await self.func(self.cog, *args, **kwargs)
      File "D:\my_python_projects\MongoDB Test\Cogs\music.py", line 537, in buttontest
        await ctx.send(
    TypeError: send() got an unexpected keyword argument 'components'
    
        @cog_ext.cog_slash(name="button", guild_ids=slash_ids)
        async def buttontest(self, ctx):
            await ctx.send(
                "Here is an example of a button",
                components=[
                    [
                        Button(style=ButtonStyle.green, label="GREEN"),
                        Button(style=ButtonStyle.red, label="RED"),
                        Button(style=ButtonStyle.grey, label="GREY", disabled=True),
                    ],
                    Button(style=ButtonStyle.blue, label="BLUE"),
                    Button(style=ButtonStyle.URL, label="URL", url="https://www.example.com"),
                ],
            )
    
    bug 
    opened by FeelsBadMan1 9
  • Add example a command(buttons navigations) with while and check

    Add example a command(buttons navigations) with while and check

    PR TYPE

    Why did you open this PR (If it is other, please write a more detailed description.)

    • [x] New feature
    • [ ] Fix bug
    • [ ] Typo
    • [ ] Other

    Checks

    • [ ] Did you use the black formatter?
    • [ ] Does this requires the users to change their code?
    • [ ] Did you test?
    • [ ] Have you updated the docs?
    • [ ] Can you listen to our requests?
    • [ ] Did you use conventional commits
    opened by helish88 7
  • Create simple.py

    Create simple.py

    PR TYPE

    Added example file. I'm planning to add more examples like calculator, etc

    Why did you open this PR (If it is other, please write a more detailed description.)

    • [ ] New feature
    • [ ] Fix bug
    • [ ] Typo
    • [x] Other

    Checks

    • [ ] Did you use the black formatter?
    • [ ] Does this requires the users to change their code?
    • [x] Did you test?
    • [ ] Have you updated the docs?
    • [x] Can you listen to our requests?
    • [ ] Did you use conventional commits
    opened by notnotrachit 7
  • Examples not working[Bug]

    Examples not working[Bug]

    Hi! I am trying the examples and the buttons are created but I am always getting "This interaction failed", I am using the last version of the library and Python 3.10.

    bug 
    opened by nfernandezsanz 6
  • Use add_listener function instead of on_socket_response

    Use add_listener function instead of on_socket_response

    In this line, I think the intention is add a socket_response listener https://github.com/kiki7000/discord.py-components/blob/49dafb8f5efa84c655649608b7ffd157b86d0040/discord_components/client.py#L86

    However, an unwanted side effect of this way of adding a listener is that it overwrites any other on_socket_response listener function already defined on the bot. I think a better solution would be to use discord.py's Bot.add_listener function:

    self.bot.add_listener(on_socket_response, name='socket_response')
    

    This listener will still be called even if some other library/user adds 'socket_response' listeners, and also won't replace existing on_socket_response methods.

    opened by burtonwilliamt 5
  • [Bug] Bot mentions regardless of its AllowedMentions

    [Bug] Bot mentions regardless of its AllowedMentions

    Excpected Action

    I've set its allowed_mentions to discord.AllowedMentions.none() and expects it not to mention anyone.

    Actual Action

    It mentions as if no filter is applied.

    Reproducing the action

    set its allowed_mentions to discord.AllowedMentions.none() declare DiscordComponents with change_discord_methods = True reply to a message

    Possible Solution

    It is happening when change_discord_methods is enabled. It is surely to cause of this issue.

    Environment

    3.9 library: most recent

    Check

    • [x] Are you using the newest version?
    • [ ] Is this bug related to security issues?
    bug 
    opened by seojin200403 4
  • [Bug] When fetching the buttons of a message, it doesn't return their rows.

    [Bug] When fetching the buttons of a message, it doesn't return their rows.

    Bug Line

    https://github.com/kiki7000/discord.py-components/blob/master/discord_components/client.py

    Excpected Action

    Return the list of buttons with the rows ([[Button1, Button2, Button3, Button4, Button5], [Button6]])

    Actual Action

    It returns a single list of buttons ([Button1, Button2, Button3, Button4, Button5, Button6])

    Reproducing the action

    Fetch a message with more than one row of buttons

    Possible Solution

    Provide the rows

    Environment

    Python 3.9.5

    Check

    • [X] Are you using the newest version?
    • [ ] Does this bug occurs security issues?
    bug 
    opened by Kanin 4
  • [Bug] Discord Buttons & Components

    [Bug] Discord Buttons & Components

    Hey. today discord released the buttons but somehow i find 2 codeexamples in the docs one use buttons and one use components. if i use the components exaple i get a json not seziable error and if i use buttons i get this:

    Ignoring exception in on_message
    Traceback (most recent call last):
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord\client.py", line 343, in _run_event
        await coro(*args, **kwargs)
      File "D:/my_python_projects/MongoDB Test/mongosetup.py", line 31, in on_message
        m = await msg.channel.send(
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord_buttons\client.py", line 57, in send_button_msg_prop
        return await self.send_button_msg(ctxorchannel, *args, **kwargs)
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord_buttons\client.py", line 150, in send_button_msg
        data = await self.bot.http.request(
      File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord\http.py", line 192, in request
        async with self.__session.request(method, url, **kwargs) as r:
    AttributeError: 'NoneType' object has no attribute 'request'
    

    anyone knows a solution?

    bug 
    opened by FeelsBadMan1 4
  • Hacktoberfest

    Hacktoberfest

    Can you please add hacktoberfest topic in this repository so that contributors can participate in that by contributing in the repository and pr for this repository can be considered for the participation.

    opened by TheShubhendra 3
Releases(2.1.2)
Instagram-Reports is a tool made to ban any scam or bad person

ABOUT TOOL : Instagram-Reports is a tool made to ban any scam or bad person. Installation : sudo apt-get update -y sudo apt-get upgrade -y apt insta

Evan Al Mahmud Irfan ථ 1 Dec 20, 2021
PS3API - PS3 API for TMAPI and CCAPI in python.

PS3API PS3 API for TMAPI and CCAPI in python. Examples Connecting and Attaching from ps3api import PS3API PS3 = PS3API(PS3API.API_TMAPI) if PS3.Conn

Adam 9 Sep 01, 2022
A delightful and complete interface to GitHub's amazing API

ghapi A delightful and complete interface to GitHub's amazing API ghapi provides 100% always-updated coverage of the entire GitHub API. Because we aut

fast.ai 428 Jan 08, 2023
Image-Bot-Discord - This Is a discord bot that shows the specific image you search from Google

Advanced Discord.py Image Bot CREDITS Made by RLX and Mathiscool README by Milrato Installation Guide in .env Adjust the TOKEN python main.py to start

RLX 3 Jan 16, 2022
GUI Pancakeswap V2 and Uniswap V3 trading client (and bot)MOST ADVANCE TRADING BOT SUPPORT WINDOWS LINUX MAC

GUI Pancakeswap 2 and Uniswap 3 trading client (and bot) (MOST ADVANCE TRADING BOT SUPPORT WINDOWS LINUX MAC) UPDATE: MUTI TRADE TOKEN ENABLE ,TRADE 1

2 Dec 27, 2021
Automatically pulls specified repository whenever a specified file is pushed. Great for working collaboratively when you need to run something locally.

autopull Simple python tool that allows you to automatically pull from a github repository whenever a file with a specified name is uploaded installat

carreb 0 Sep 27, 2022
Project made to analyse movie trends

MovieTrends Project to analyse the daily movie trends from the website The Movie DataBase. The main idea is upload the results to a PostgreSQL server

Jazmín López Chacón 0 Feb 15, 2022
An analysis of the efficiency of the COVID-19 vaccine

VaccineEfficiency 💉 An analysis of the efficiency of the COVID-19 vaccine 3 Methods 1️⃣ Compare country's vaccination data to number of day- to-day c

Stephanie Younes 1 Dec 10, 2021
TonplaceApi - Ton.place api wrapper

tonplaceApi ton.place/tonplaceApi Обертка для ton.place Установка pip install ht

Nickolay Samedov 3 Feb 21, 2022
Heroku app to explore boardgame data

A Dashboard for the Board Game Geeks among us Link to Application As many Board Game Geeks like myself track the scores of board game matches I decide

Maarten Grootendorst 20 Nov 23, 2022
Periodically check the manuscript state in the scholar one system and send email when finding a new state.

ScholarOne-manuscript-checker Periodically check the manuscript state in the scholar one system and send email when finding a new state. Parameters ne

2 Aug 18, 2022
A simple script & container to pull COVID data from covidlive.com.au and post a summary to a slack channel

CovidLive AU Summary Slackbot This bot is a very simple slackbot that pulls data, summarises and posts up to date AU COVID stats to a provided slack c

James 3 Dec 18, 2021
WikiChecker - Repositorio oficial del complemento WikiChecker para NVDA.

WikiChecker Buscador rápido de artículos en Wikipedia. Introducción. El complemento WikiChecker para NVDA permite a los usuarios consultar de forma rá

2 Jan 10, 2022
Automate coin farming for dankmemer. Unlimited accounts at once. Uses a proxy

dankmemer-farm Simple script to farm Dankmemer coins with multiple accounts at once. Requires: Proxies, Discord Tokens Disclaimer I don't take respons

Scobra 12 Dec 20, 2022
A simple fun discord bot using discord.py that can post memes

A simple fun discord bot using discord.py * * Commands $commands - to see all commands $meme - for a random meme from the internet $cry - to make the

Dice Flip 2 Dec 20, 2021
A anti-repostbot script for reddit, runs u/ThisIsARepostBotBot

ThisIsARepostBotBot So you found a repost bot, now what? This is a bot to reply to all posts of a repost bot with a message urging users to report and

3 May 23, 2022
Бот - Гуль для твоего телеграм аккаунта

Я - Гуль (бот), теперь работает в чатах Отблагодарить автора за проделанную работу можно здесь Помощь с установкой тут Установка на Андроид После уста

57 Nov 06, 2022
A simple telegram bot to help you to remove forward tag from post from any messages . Maded in python3 using @Pyrogram . Developed by @Kunal-Diwan

Frwd-Tag-Remover Telegram Bot to Remove forward tag from any Post . If you need any more modes in repo or If you find out any bugs, mention in @Develo

Kunal Diwan 2 Oct 14, 2022
Discord-Bot - Bot using nextcord for beginners

Discord-Bot Bot using nextcord for beginners! Requirements: 1 :- Install nextcord by typing "pip install nextcord" Thats it! You can use this code any

INFINITE_. 3 Jan 10, 2022
A Telegram bot to extracting text from images. All languages supported.

OCR Bot A Telegram bot to extracting text from images. All languages supported. Deploy to Heroku Local Deploying Clone the repo git clone https://gith

6 Oct 21, 2022