Useful tools for building interactions in Python

Overview

discord-interactions-python

PyPI - License PyPI - Python Version

Types and helper functions for Discord Interactions webhooks.

Installation

Available via pypi:

pip install discord-interactions

Usage

Use the InteractionType and InteractionResponseType enums to process and respond to webhooks.

Use verify_key to check a request signature:

if verify_key(request.data, signature, timestamp, 'my_client_public_key'):
    print('Signature is valid')
else:
    print('Signature is invalid')

Use verify_key_decorator to protect routes in a Flask app:

import os

from flask import Flask, request, jsonify

from discord_interactions import verify_key_decorator, InteractionType, InteractionResponseType

CLIENT_PUBLIC_KEY = os.getenv('CLIENT_PUBLIC_KEY')

app = Flask(__name__)

@app.route('/interactions', methods=['POST'])
@verify_key_decorator(CLIENT_PUBLIC_KEY)
def interactions():
  if request.json['type'] == InteractionType.APPLICATION_COMMAND:
    return jsonify({
        'type': InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
        'data': {
            'content': 'Hello world'
        }
    })

Exports

This module exports the following:

InteractionType

An enum of interaction types that can be POSTed to your webhook endpoint.

InteractionResponseType

An enum of response types you may provide in reply to Discord's webhook.

InteractionResponseFlags

An enum of flags you can set on your response data.

verify_key(raw_body: str, signature: str, timestamp: str, client_public_key: str) -> bool:

Verify a signed payload POSTed to your webhook endpoint.

verify_key_decorator(client_public_key: str)

Flask decorator that will verify request signatures and handle PING/PONG requests.

Comments
  • [Minor] Method parameter type incorrect

    [Minor] Method parameter type incorrect

    The raw_body parameter type should be bytes and not str.

    https://github.com/discord/discord-interactions-python/blob/d0c5b42840067692bcb37dae631dada1d2e6b497/discord_interactions/init.py#L25

    opened by enderCoder99 1
  • Decorator triggers exception when receiving a request from a source other than Discord.

    Decorator triggers exception when receiving a request from a source other than Discord.

    Description

    Currently, if the method wrapped by the verify_key_decorator decorator receives a request that doesn't contain either of the X-Signature-* headers, or a body without the type key, it will result in an exception that will trigger a 500 error. This isn't particularly problematic given that requests from any source other than Discord should be rejected anyway, but it would be preferable to respond with a 403 error instead so that these errors are not included in the logs of the application.

    Steps to reproduce

    1. Handle slash commands with something like the code included in the project's current README:
    @verify_key_decorator(CLIENT_PUBLIC_KEY)
    def interactions():
      if request.json['type'] == InteractionType.APPLICATION_COMMAND:
        return jsonify({
            'type': InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
            'data': {
                'content': 'Hello world'
            }
        })
    
    1. Manually make a request to the bot's interactions endpoint (Using for example a web browser).
    2. Observe that a 500 error is produced.

    Additional Details

    In the case of the missing headers, the exception may look something like this (Though the traceback probably won't include the google cloud stuff):

    Traceback (most recent call last):
      File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
        response = self.full_dispatch_request()
      File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
        rv = self.handle_user_exception(e)
      File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
        reraise(exc_type, exc_value, tb)
      File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
        raise value
      File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
        rv = self.dispatch_request()
      File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
        return self.view_functions[rule.endpoint](**req.view_args)
      File "/layers/google.python.pip/pip/lib/python3.8/site-packages/functions_framework/__init__.py", line 66, in view_func
        return function(request._get_current_object())
      File "/layers/google.python.pip/pip/lib/python3.8/site-packages/discord_interactions/__init__.py", line 44, in __decorator
        if not verify_key(request.data, signature, timestamp, client_public_key):
      File "/layers/google.python.pip/pip/lib/python3.8/site-packages/discord_interactions/__init__.py", line 24, in verify_key
        message = timestamp.encode() + raw_body
    AttributeError: 'NoneType' object has no attribute 'encode'
    

    The NoneType in this case is the None returned by request.headers.get('X-Signature-Timestamp') since that header is not present in the request.

    opened by creallfluharty 1
  • Bump py from 1.9.0 to 1.10.0

    Bump py from 1.9.0 to 1.10.0

    Bumps py from 1.9.0 to 1.10.0.

    Changelog

    Sourced from py's changelog.

    1.10.0 (2020-12-12)

    • Fix a regular expression DoS vulnerability in the py.path.svnwc SVN blame functionality (CVE-2020-29651)
    • Update vendored apipkg: 1.4 => 1.5
    • Update vendored iniconfig: 1.0.0 => 1.1.1
    Commits
    • e5ff378 Update CHANGELOG for 1.10.0
    • 94cf44f Update vendored libs
    • 5e8ded5 testing: comment out an assert which fails on Python 3.9 for now
    • afdffcc Rename HOWTORELEASE.rst to RELEASING.rst
    • 2de53a6 Merge pull request #266 from nicoddemus/gh-actions
    • fa1b32e Merge pull request #264 from hugovk/patch-2
    • 887d6b8 Skip test_samefile_symlink on pypy3 on Windows
    • e94e670 Fix test_comments() in test_source
    • fef9a32 Adapt test
    • 4a694b0 Add GitHub Actions badge to README
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • AttributeError: 'tuple' object has no attribute 'get'

    AttributeError: 'tuple' object has no attribute 'get'

    I'm trying to add my interactions endpoint url to my app in discord, using a python flask app.

    I'm running the example in the README.md and there is a failure when verifying the content of the type :

    x.x.x.x - - [26/Aug/2021 16:26:43] "POST /interactions HTTP/1.1" 401 -
    [2021-08-26 16:26:43,604] ERROR in app: Exception on /interactions [POST]
    Traceback (most recent call last):
      File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1982, in wsgi_app
        response = self.full_dispatch_request()
      File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
        rv = self.handle_user_exception(e)
      File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1517, in handle_user_exception
        reraise(exc_type, exc_value, tb)
      File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 33, in reraise
        raise value
      File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
        rv = self.dispatch_request()
      File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1598, in dispatch_request
        return self.view_functions[rule.endpoint](**req.view_args)
      File "/usr/local/lib/python3.7/site-packages/discord_interactions/__init__.py", line 48, in __decorator
        if request.json and request.json.get('type') == InteractionType.PING:
    AttributeError: 'tuple' object has no attribute 'get'
    x.x.x.x - - [26/Aug/2021 16:26:43] "POST /interactions HTTP/1.1" 500 -
    

    How can I add my interactions endpoint url if discord can't verify it ?

    Tested with Python 3.7 and 3.8.

    opened by fmdaboville 0
  • Add decorator to register/update slash commands with Discord?

    Add decorator to register/update slash commands with Discord?

    Would it be in scope for this project to add a decorator to update Discord with changes to slash commands when the flask service is started/reloaded in debug mode for faster development? There would likely need to be some way to store bot token as authentication in the flask app, maybe a wrapper of some kind. as an example:

    from discord_interactions import verify_key_decorator, SlashCommand
    
    app = Flask(__name__)
    sc = SlashCommand(app)
    sc.token = environ["BOT_TOKEN"] # also retrieves application client ID
    sc.guild_id = guild_id # optional, limits all commands on this service to a guild, would also be configurable from each decorator
    
    def get_opts(name):
        with open("options.json") as f
            return json.load(f)[name]
    
    @app.route("/", methods=["POST"])
    @verify_key_decorator(PUBKEY) # could be implicit with inclusion of SlashCommand.command
    @sc.command(name="watch", description=long_desc, options=get_opts("watch")) # , guild_id=guild_id)
    def watch():
        pass
    

    If this type of behaviour is not in scope I'll start up a separate project to provide this functionality.

    opened by alyssadev 0
Owner
Discord
A new way to chat with your communities and friends. Discord is the easiest way to communicate over voice, video, and text.
Discord
Discord Panel is an AIO panel for Discord that aims to have all the needed tools related to user token interactions, as in nuking and also everything you could possibly need for raids

Discord Panel Discord Panel is an AIO panel for Discord that aims to have all the needed tools related to user token interactions, as in nuking and al

null 11 Mar 30, 2022
A small and fun Discord Bot that is written in Python and discord-interactions (with discord.py)

Articuno (discord-interactions) A small and fun Discord Bot that is written in Python and discord-interactions (with discord.py) Get started If you wa

Blue 8 Dec 26, 2022
Typed interactions with the GitHub API v3

PyGitHub PyGitHub is a Python library to access the GitHub API v3 and Github Enterprise API v3. This library enables you to manage GitHub resources su

null 5.7k Jan 6, 2023
๐Ÿ“ท Instagram Bot - Tool for automated Instagram interactions

InstaPy Tooling that automates your social media interactions to โ€œfarmโ€ Likes, Comments, and Followers on Instagram Implemented in Python using the Se

Tim GroรŸmann 13.5k Dec 1, 2021
This package allows interactions with the BuyCoins API.

The BuyCoins Python library allows interactions with the BuyCoins API from applications written in Python.

Abdulazeez Abdulazeez Adeshina 45 May 23, 2022
It is a temporary project to study discord interactions. You can set permissions conveniently when you invite a particular disk code bot.

Permission Bot ๋””์Šค์ฝ”๋“œ ๋‚ด์— ์žˆ๋Š” message-components ๋ฅผ ์—ฐ๊ตฌํ•˜๊ธฐ ์œ„ํ•˜์—ฌ ์ œ์ž‘๋œ ๋ด‡์ž…๋‹ˆ๋‹ค. Setup /config/config_example.ini ํŒŒ์ผ์„ /config/config.ini์œผ๋กœ ๋ณ€ํ™˜ํ•ฉ๋‹ˆ๋‹ค. config ํŒŒ์ผ์˜ ๊ธฐ๋ณธ ์–‘์‹์€ ์•„

gunyu1019 4 Mar 7, 2022
Unit testing AWS interactions with pytest and moto. These examples demonstrate how to structure, setup, teardown, mock, and conduct unit testing. The source code is only intended to demonstrate unit testing.

Unit Testing Interactions with Amazon Web Services (AWS) Unit testing AWS interactions with pytest and moto. These examples demonstrate how to structu

AWS Samples 21 Nov 17, 2022
A discord http interactions framework built on top of Sanic

snowfin An async discord http interactions framework built on top of Sanic Installing for now just install the package through pip via github # Unix b

kaj 13 Dec 15, 2022
Boilerplate template for the discord-py-interactions library

discord-py-interactions_boilerplate Boilerplate template for the discord-py-interactions library Currently, this boilerplate supports discord-py-inter

Ventus 7 Dec 3, 2022
A secure and customizable bot for controlling cross-server announcements and interactions within Discord

DiscordBot A secure and customizable bot for controlling cross-server announcements and interactions within Discord. Within the code of the bot, you c

Jacob Dorfmeister 1 Jan 22, 2022
ToqueIO Nuke tools - A collection of tools designed to assist in enhancing your workflows within nuke

ToqueIO Nuke tools - A collection of tools designed to assist in enhancing your workflows within nuke

null 4 Feb 19, 2022
IMDbPY is a Python package useful to retrieve and manage the data of the IMDb movie database about movies, people, characters and companies

IMDbPY is a Python package for retrieving and managing the data of the IMDb movie database about movies, people and companies. Revamp notice Starting

Davide Alberani 1.1k Jan 2, 2023
A simple Discord bot wrote with Python. Kizmeow let you track your NFT project and display some useful information

Kizmeow-OpenSea-and-Etherscan-Discord-Bot ไธญๆ–‡็‰ˆ | English Ver A Discord bot wrote with Python. Kizmeow let you track your NFT project and display some u

Xeift 93 Dec 31, 2022
Algofi Python SDK is useful for developers who want to programatically interact with the Algofi lending protocol

algofi-py-sdk Algofi Python SDK Documentation https://algofi-py-sdk.readthedocs.

Algofi 41 Dec 15, 2022
An simple python script for remove rockstar account for fivem, very useful for cheating or change account for unban from an server, remember change steam account.

This tool is used for be unbanned from servers, u need disconnect the discord, use other steam account and uninstall xbox for be unbanned 100%, it only work for unban in server, not global

MiguDEV 4 Oct 10, 2022
A Open source Discord Token Grabber with several very useful features coded in python 3.9

Kiwee-Grabber A Open source Discord Token Grabber with several very useful features coded in python 3.9 This only works on any python 3.9 versions. re

Vesper 40 Jan 1, 2023
Telegram Group Calls Streaming bot with some useful features, written in Python with Pyrogram and Py-Tgcalls. Supporting platforms like Youtube, Spotify, Resso, AppleMusic, Soundcloud and M3u8 Links.

Yukki Music Bot Yukki Music Bot is a Powerful Telegram Music+Video Bot written in Python using Pyrogram and Py-Tgcalls by which you can stream songs,

Team Yukki 996 Dec 28, 2022
Simple script to extract useful informations from the combo BloodHound + Neo4j

bloodhound-quickwin Simple script to extract useful informations from the combo BloodHound + Neo4j. Can help to choose a target. Prerequisites python3

null 140 Dec 21, 2022