Let's build Bots for STEEM - Part 04: A first bot for Discord

in #steem7 years ago

Hi Steemians, let's build BOTS!

On this blog I want to document my progress in implementing bots for the STEEM blockchain.


Image Source: https://pixabay.com/de/roboter-computer-bots-charakter-764951/

In my last post I install steem-python on Ubuntu 17.10 and started a first script.

Today I want to build a first bot for Discord to get notified in discord when new post with a hashtag like "utopian-io" is posted.

A new Discord App

First log into discordapp.com and open the following url:

https://discordapp.com/developers/applications/me

Click the New App icon.

On this screen define the name of your app, a description and upload an avatar image. Finally click Create App.

Discord has also created a new Client ID for your app. Copy and paste this ID, you will need it later.

It's also necessary to create a bot user too. Click the Create a Bot User Button.

And confirm with Yes, do it!.

At this page you can see your secret token. Never share this value. You need this token to connect your bot to discord. Please note that I have changed the token for my bot-user, so don't try to use it.

Now it's time to add your new bot-user to an discord-channel. For testing purposes i created my own "botsultant" discord server, and with this url I add the new bot to the server. Please note that you need to replace the CLIENT_ID in the URL. You find your client id in your discord settings.

https://discordapp.com/oauth2/authorize?client_id=CLIENT_ID&scope=bot&permission=0

Select one your servers (you need to be owner of the server) and add the bot.

That was easy.

The Code

Now it's time to open a connection from python to discord. I've re-used the script from my last post and added some discord stuff. The idea of the bot is to post all new posts with hashtag utopian-io in a chat channel. Here is the full bot-code (without any kind of exception handling).

from steem.blockchain import Blockchain
from steem.post import Post
from steem.instance import set_shared_steemd_instance
from steem.steemd import Steemd
from steem.steem import Steem
import discord
import asyncio

def get_channel(channels, channel_name):
    for channel in client.get_all_channels():
        print(channel)
        if channel.name == channel_name:
            return channel
    return None

client = discord.Client()

@client.event
async def on_ready():
    print("Logged in")
    general_channel = get_channel(client.get_all_channels(), 'general')
    await client.send_message(general_channel, 'Hello Discord')

    steem_url = 'https://steemd.pevo.science'
    steemd_nodes = [steem_url]
    set_shared_steemd_instance(Steemd(nodes=steemd_nodes))
    steem = Steem()
    b = Blockchain()
    s = map(Post, b.stream(filter_by=['comment']))

    for post in s:
        if post.is_main_post():
            if "utopian-io" in post["tags"]:
                url = 'https://steemit.com/tag/@' + post['author'] + '/' + post['permlink']
                await client.send_message(general_channel, url)

client.run("SECRET_TOKEN")

The Result

As result I got links to new utopian-io posts in my discord channel.

Some Details

Finally some words to the bot code.

Install discord.py

First of all you need to install the discord python librarys. All you need is

pip3 install discord.py

Import the libraries

Add the following imports to your python script.

import discord
import asyncio

Hello Discord

The on_ready() function is called by discord.py as soon as our bot is connected to discord. This peace of code sends a Hello Discord into the chat-room.

@client.event
async def on_ready():
    print('Logged in')
    general_channel = get_channel(client.get_all_channels(), 'general')
    await client.send_message(general_channel, 'Hello Discord')

Start the bot

First you need to create an client instance. You start your bot with the run method. You need to provide your secret token there.

client = discord.Client()
...
client.run("SECRET_TOKEN")

Filter the posts

Once the bot is running, we loop over all new posts. In case one off the tags is utopian-io, we forward the url of the post to our discord channel.

    b = Blockchain()
    s = map(Post, b.stream(filter_by=['comment']))

    for post in s:
        if post.is_main_post():
            if "utopian-io" in post["tags"]:
                url = 'https://steemit.com/tag/@' + post['author'] + '/' + post['permlink']
                await client.send_message(general_channel, url)

What's next?

My bot failed after some minutes, because no exception handling is implemented. In the next post I will harden the bot. Stay tuned.

Sort:  

Thank you for this post - I will try to do this myself. I have played around with piston a little bit, I got it to work but have not figured out some of the functions yet. @felixxx, do you know how I can get the latest data from wallet transactions?I am trying to figure out programming a bid bot but have no idea how to get this data.

Bookmarked for later.

I am planning on moving some of @deutschbot's functions to Discord.