Thursday, March 23, 2023
HomeRuby On RailsDevelop a Dissonance Robot with Python and also Flask

Develop a Dissonance Robot with Python and also Flask


Dissonance is a system that makes it possible for individuals to discuss voice, video clip, and also message, along with associate their good friends and also neighborhoods. Dissonance offers a method to area various teams of individuals with Server/Guild.

In this short article, you will certainly find out just how to make use of some functions offered by Dissonance API. We will certainly start by clarifying just how to establish Dissonance OAuth2 for verification, complied with by constructing a basic disharmony crawler and also affixing it to some web servers, and also lastly, presenting the web servers where the crawler is affixed on the frontend.

When collaborating with Dissonance, a great deal of performance will certainly require to be taken care of asynchronously due to the fact that Dissonance utilizes WebSockets to construct real-time interaction in between the Dissonance API and also the application. Keeping that claimed, we will certainly need to make use of a variation of Flask that deal with asynchronous demands completely Quart

You can locate the complete job on GitHub

Requirements

  • Fundamental understanding of Python and also Flask.
  • Python set up.
  • Dissonance account and also regarding 5 web servers developed.

Authenticate Dissonance with OAuth2

Later on in this short article, we will certainly be constructing something like a control panel where you can see all the web servers that have your crawler affixed to it. You might not desire every person to be able to accessibility that web page, so you can make use of the OAuth2 system offered by Dissonance.

To do this, most likely to the Dissonance programmer site, and also * ** on the Dissonance programmer portal web page, click the “ New Application *” switch in the leading right edge. After that, fill in the “Call” area and also send.

Next off, click the OAuth2 dropdown and after that click the Include Redirect switch. This is where you will certainly include the link that will certainly deal with the redirect after verification. The link we will certainly be making use of for the redirect is http://127.0.0.1:5000/callback Additionally, keep in mind of the CUSTOMER ID and also CUSTOMER KEY due to the fact that we will certainly require them in the code.

Set OAuth2 callback URL
Establish OAuth2 callback link

On the OAuth2 dropdown, click the Link Generator tab and also choose the range that you see on the picture listed below. After that, replicate the link produced. This link will certainly be made use of to attach the crawler to the web server.

URL generator page
link generator web page

Open Up the link on the web browser, choose the web server you wish to attach the crawler to it, and also send all the redirects.

Currently, allow’s mount the reliances with the complying with command.

 pip  mount  quart quart-discord discord-ext-ipc disharmony

Structure the Verification System

Initially, produce a brand-new data with name main.py and also paste the complying with code. The code listed below is booting up the qualifications and also paths needed to verify with Dissonance.

 from  quart  import  Quart,  render_template,  redirect,  url_for
 from  quart_discord  import  DiscordOAuth2Session
 import  os

 os environ[
    "OAUTHLIB_INSECURE_TRANSPORT"
]  = " 1"   # this is needed due to the fact that OAuth 2 uses https.

 application  =  Quart( __ name __)

 application config["SECRET_KEY"]  = " test123"

 application config["DISCORD_CLIENT_ID"]  =  969522874446671953   # Dissonance customer ID.
 application config[
    "DISCORD_CLIENT_SECRET"
]  = " dfp9GSgUHqvIMBSEIsrG9DW1XMnJskhl"   # Dissonance customer key.
 application config[
    "DISCORD_REDIRECT_URI"
]  = " http://127.0.0.1:5000/callback"   # link to your callback endpoint.

 disharmony  =  DiscordOAuth2Session( application)  #handle session for verification

 @ application course(" https://www.honeybadger.io/")
 async  def  residence(): 
     return  wait for  render_template(" home.html",  accredited = wait for  disharmony accredited)

 @ application course("/ login")
 async  def  login(): 
     return  wait for  disharmony create_session()  # takes care of session production for verification

 @ application course("/ callback")
 async  def  callback(): 
     attempt: 
         wait for  disharmony callback()
     other than  Exemption: 
         pass

     return  redirect( url_for(" control panel"))  #dashboard feature will be developed later on in the a.

Keep in mind the qualifications I informed you to keep in mind of earlier? You will certainly require to input them in the code over. If you are constructing a real-world job, you will certainly require to make certain to maintain those qualifications safeguard.

If you discover in the code over, we made use of a data home.html; this is the web page that the will certainly deal with the verification switch. In the exact same folder where main.py lies, produce a brand-new directory site and also data templates/home. html and also paste the code listed below.

<
<< html>>
<< head>>
    << title>> Web Page<
<
<< body>>
<< h1>> Welcome to the Web page!<

Go here to login:.
<< a  href ="/ login"><> < switch>> Login with disharmony< 

<
<

Developing the Dissonance Robot

In this area, we will certainly be developing a basic crawler that claims, “Hey there There!”, when it is sounded. To achieve this, we will certainly make use of 2 devices that we set up previously: discord-ext-ipc and also disharmony disharmony is a Dissonance collection for Python, and also discord-ext-ipc offers a web server for crawler solutions.

Begin by developing a data called bot.py and also paste the complying with code. The code listed below sends out “Hi there!” anytime it is sounded.

 import  disharmony
 from  discord.ext  import  commands,  ipc

 course  MyBot( commands Robot): 
     def  __ init __( self,  * args,  ** kwargs): 
         very(). __ init __( * args,  ** kwargs)

         self ipc  =  ipc Web Server( self,  secret_key =" this_is_secret")  #used tonnect ipc web server to various other web servers.

     async  def  on_ready( self): 
        """ Contacted the all set occasion"""
         print(" Robot prepares.")

     async  def  on_ipc_ready( self): 
        """ Contacted the IPC Web server preparing"""
         print(" Ipc web server prepares.")

     async  def  on_ipc_error( self,  endpoint,  mistake): 
        """ Contacted a mistake being increased within an IPC course"""
         print( endpoint, " increased",  mistake)

 my_bot  =  MyBot( command_prefix ="$",  intents = disharmony Intents default())  #prefix to sound the crawler.

 @ my_bot command()
 async  def  hi( ctx):  
     wait for  ctx send out(" Hi there!")  # reaction from the crawler when you send out $hi.

 my_bot ipc begin()
 my_bot run(" OTY5NTIyODc0NDQ2NjcxOTUz.Ymuoig.OMsQ8sCsk5pY1cJSdn5yyDB8Bhc")

For the crawler to function, you require to obtain the crawler token from the Dissonance programmer site, in the Robot tab.

Get Discord bot token
Obtain Dissonance crawler token

Structure the Control Panel

To construct the control panel, we require compose features in bot.py to obtain the variety of guilds where the crawler exists and also the guild IDs of the guilds where the crawler exists. We require the guild IDs for the crawler to make sure that we can match it with the listing of all individual guilds that we enter the application ( main.py), and after that present the guild’s information where they match.

You can do this by pasting the complying with code over my_bot. ipc.start() in your bot.py data.

 @ my_bot ipc course()
 async  def  get_guild_count( information): 
     return  len( my_bot guilds)   # returns the len of the guilds to the customer.

 @ my_bot ipc course()
 async  def  get_guild_ids( information): 
     last  = []
     for  guild  in  my_bot guilds: 
         last append( guild id)
     return  last   # returns the guild ids where the crawler is.

Currently we require to compose the feature for the control panel in the main.py data. Paste the complying with code, listed below in callback()

 @ application course("/ control panel")
 async  def  control panel(): 
     guild_count  =  wait for  ipc_client demand(" get_guild_count")  # obtain func we developed aearlier for guild matter.
     guild_ids  =  wait for  ipc_client demand(" get_guild_ids")  # obtain func we developed aearlier for guild IDs.

     attempt: 
         user_guilds  =  wait for  disharmony fetch_guilds()  # bring information for individual's guilds.
         individual  =  wait for  disharmony fetch_user()  #fetch information for individual.
     other than: 
         return  redirect( url_for(" login"))  # reroute to login web page if individual is not visited.

     same_guilds  = []

     for  guild  in  user_guilds: 
         if  guild id  in  guild_ids: 
             same_guilds append( guild)

     return  wait for  render_template(
        " dashboard.html",  guild_count = guild_count,  matching = same_guilds,  individual = individual
    )

 if  __ name __ = = " __ major __": 
     application run( debug = Real)

After that include the code listed below to the top of the main.py data.

 from  discord.ext  import  ipc 

 ipc_client  =  ipc Customer(
     secret_key =" this_is_token"
)   # secret_key should coincide as your IPC web server.

You might have observed in control panel() that we are providing a design template ( dashboard.html) we have actually not developed.

Develop a brand-new data with the name dashboard.html in themes/ and also paste the complying with code.

<
<< html>>
<< head>>
    << title>> Control Panel<
<
<< body>>
  << h3>> Hi, {{user.name}}! Please choose a web server to start<

<< h2>> The Robot remains in: {{guild_count}} web servers <

<< h3>> Robot's guilds <

<< ul>>
{% for guild in matching %}
<< img  src =" {{guild.icon _ link}} "  />>
  << li>> {{guild.name}} <
  << br><> < br>>
{% endfor %}
<

<
<

Evaluating

To start, allow’s begin the web server for the crawler and also the application. You can begin the web server for the crawler by running python bot.py, and also you can begin the application on an additional command-line home window with python main.py Currently most likely to Dissonance and also choose among the guilds/servers to which you affixed the crawler, and also you will certainly discover on the leading right that your crawler is energetic. Sound the crawler by texting “$ hi”, and also you ought to obtain “Hey there There!” as the reaction.

Output from the whole code
Outcome from the entire code

You can check the application by mosting likely to localhost for Flask; struck the login switch to visit, and after that you will certainly be rerouted to the control panel.

Dashboard display
Control panel screen

Verdict

In this short article, you have actually found out just how to make use of each attribute offered by Dissonance API. Initially, we found out just how to establish Dissonance OAuth2 for verification. After that, we developed a basic disharmony crawler and also affixed it to some servers/guilds. Ultimately, we presented the web servers where we affixed the crawler on the frontend.

You might have observed that in the tutorial, I really did not take note of the layout of the application. This might be where you can enhance where I ended. Naturally, you can constantly enhance the intricacy of the crawler as required.

Ultimately, please bear in mind to constantly safeguard your Dissonance qualifications.

RELATED ARTICLES

Most Popular

Recent Comments