create account

Part 6: How To Automatically Reply To Mentions Using Steem-Python by steempytutorials

View this thread on: hive.blogpeakd.comecency.com
· @steempytutorials · (edited)
$33.51
Part 6: How To Automatically Reply To Mentions Using Steem-Python
<center>![steem-python.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1515886103/kmzfcpvtzuwhvqhgpyjp.png)</center>

This tutorial is part of a series where we explain different aspects of programming with `steem-python`. Links to the other tutorials can be found in the curriculum section below. Today we will learn how to stream the blockchain and see who mentions you using `steem-python`!

---

#### What will I learn

- How to create a regular expression
- How to find people mentioning you
- How to reply to them

#### Requirements

- Python3.6
- `steem-python`
- `re`

#### Difficulty

- Basic

---

### Tutorial
#### Streaming the blockchain for mentions
We have already gone over how to stream the blockchain in [part 2 of this tutorial series](https://utopian.io/utopian-io/@steempytutorials/part-2-how-to-stream-and-filter-the-blockchain-using-steem-python), so if you need to, read up about it there. In the previous tutorials we could simply filter the blockchain for the operations we wanted, for example posts or votes, but unfortunately mentions aren't an operation on the blockchain. What this means is that the best way to find out who mentions you is to stream all posts on the blockchain and then check its body to see if someone has mentioned you. So once again, we simply stream all posts on the blockchain like so

```
from steem import Steem
from steem.blockchain import Blockchain
from steem.post import Post

steem = Steem()
blockchain = Blockchain()
stream = map(Post, blockchain.stream(filter_by=["comment"]))

for post in stream:
    # DO SOMETHING
```

#### Creating a regular expression
To find out who mentions us we should read the body of each post and find out if it contains `@username`. A great way to do this is by using a [regular expression](https://docs.python.org/3/howto/regex.html). We can use a regular expression to specify the rules for the string that we want to match, a mention in this case. Luckily a good regex to do this can be found [here](https://stackoverflow.com/questions/2304632/regex-for-twitter-username)

```
(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9]+)
```

We can then use the function `findall()` to create a list of all mentions in a post. Once we have this we can simply check if our username is in the given list! An example is given below

```
text = "hello @amosbastian and @juliank I love @steempytutorials, contact me at username@hotmail.com"
mentions = re.findall("(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9]+)", text)
print(mentions)
```

which outputs

```
['amosbastian', 'juliank', 'steempytutorials']
```

#### Mentions on the blockchain

So now we know how to find mentions in a string we can use this to find mentions in the body of posts. To do this we can use the regex we created above and do the following

```
REGEX = "(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9]+)"
username = "steempytutorials"

while True:
    try:
        for post in stream:
            mentions = re.findall(REGEX, post["body"])
            if username in mentions:
                print(f"{post['author']} just mentioned you!")

    except Exception as error:
        print(repr(error))
        continue
```

Running this program and testing it showed the following

```
$ python mentions.py 
amosbastian just mentioned you!
```
#### Replying to mentions

If someone mentions you, you could do many things, but for the sake of this tutorial we are simply going to reply to them. To this we can use the `reply()` function, which makes replying to a post very simple! Instead of printing the post we will change it to

```
post.reply(f"Hey @{post['author']} thanks for mentioning me!")
```
and indeed, it works as expected

<center>![reply_mention.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1516212007/vxg8yhopctfrorjtrvtx.png)</center>

**Congratulations**, you can now automatically reply to anyone who mentions you using `steem-python`!

#### Curriculum
- [Part 0: How To Install Steem-python, The Official Steem Library For Python](https://utopian.io/utopian-io/@amosbastian/how-to-install-steem-python-the-official-steem-library-for-python)
- [Part 1: How To Configure The Steempy CLI Wallet And Upvote An Article With Steem-Python](https://utopian.io/utopian-io/@steempytutorials/part-1-how-to-configure-the-steempy-cli-wallet-and-upvote-an-article-with-steem-python)
- [Part 2: How To Stream And Filter The Blockchain Using Steem-Python](https://utopian.io/utopian-io/@steempytutorials/part-2-how-to-stream-and-filter-the-blockchain-using-steem-python)
- [Part 3: Creating A Dynamic Upvote Bot That Runs 24/7](https://steemit.com/utopian-io/@steempytutorials/part-3-creating-a-dynamic-upvote-bot-that-runs-24-7-first-weekly-challenge-3-steem-prize-pool)
- [Part 4: How To Follow A Voting Trail Using Steem-Python](https://utopian.io/utopian-io/@steempytutorials/part-4-how-to-follow-a-voting-trail-using-steem-python)
- [Part 5: Post An Article Directly To The Steem Blockchain And Automatically Buy Upvotes From Upvote Bots](https://utopian.io/utopian-io/@steempytutorials/part-5-post-an-article-directly-to-the-steem-blockchain-and-automatically-buy-upvotes-from-upvote-bots)
    
---

The code for this tutorial can be found on [GitHub](https://github.com/amosbastian/steempy-tutorials/blob/master/part_6/mentions.py)!

This tutorial was written by @amosbastian in conjunction with @juliank.

<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@steempytutorials/part-6-how-to-automatically-reply-to-mentions-using-steem-python">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorsteempytutorials
permlinkpart-6-how-to-automatically-reply-to-mentions-using-steem-python
categoryutopian-io
json_metadata{"community":"utopian","app":"steemit/0.1","format":"markdown","repository":{"id":84843862,"name":"steem-python","full_name":"steemit/steem-python","html_url":"https://github.com/steemit/steem-python","fork":false,"owner":{"login":"steemit"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","steemdev","programming","python","tutorial"],"users":["amosbastian","juliank"],"links":["https://utopian.io/utopian-io/@steempytutorials/part-2-how-to-stream-and-filter-the-blockchain-using-steem-python","https://docs.python.org/3/howto/regex.html","https://stackoverflow.com/questions/2304632/regex-for-twitter-username","https://utopian.io/utopian-io/@amosbastian/how-to-install-steem-python-the-official-steem-library-for-python","https://utopian.io/utopian-io/@steempytutorials/part-1-how-to-configure-the-steempy-cli-wallet-and-upvote-an-article-with-steem-python","https://steemit.com/utopian-io/@steempytutorials/part-3-creating-a-dynamic-upvote-bot-that-runs-24-7-first-weekly-challenge-3-steem-prize-pool","https://utopian.io/utopian-io/@steempytutorials/part-4-how-to-follow-a-voting-trail-using-steem-python","https://utopian.io/utopian-io/@steempytutorials/part-5-post-an-article-directly-to-the-steem-blockchain-and-automatically-buy-upvotes-from-upvote-bots","https://github.com/amosbastian/steempy-tutorials/blob/master/part_6/mentions.py","https://utopian.io/utopian-io/@steempytutorials/part-6-how-to-automatically-reply-to-mentions-using-steem-python"],"image":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1515886103/kmzfcpvtzuwhvqhgpyjp.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1516212007/vxg8yhopctfrorjtrvtx.png"],"moderator":{"account":"emrebeyler","time":"2018-01-17T21:17:58.138Z","reviewed":true,"pending":false,"flagged":false}}
created2018-01-17 18:05:18
last_update2018-01-19 17:02:27
depth0
children8
last_payout2018-01-24 18:05:18
cashout_time1969-12-31 23:59:59
total_payout_value25.886 HBD
curator_payout_value7.621 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length5,613
author_reputation31,094,047,689,691
root_title"Part 6: How To Automatically Reply To Mentions Using Steem-Python"
beneficiaries
0.
accountutopian.pay
weight2,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id30,226,103
net_rshares5,057,040,259,754
author_curate_reward""
vote details (28)
@emrebeyler ·
$0.11
Thank you for the contribution. It has been approved.

Btw, I have a couple of ideas about this post:

**Node issue**

```stream = map(Post, blockchain.stream(filter_by=["comment"]))```

This shouldn't work since default node defined at steem-python is *steemd.steemit.com* and it's down for a while. So, if you make it compatible with the jussi or another public node for the potential readers trying out the code, that would be perfect.

**Mentions**

We can use ```post.get("json_metadata", {}).get("users")``` to get mentions. I am not sure twitter username regex has a full compliance with steemit blockchain's username restrictions. Are there any specific reason to use a regex pattern?

Great job on the series! Looking forward to see more.


You can contact us on [Discord](https://discord.gg/uTyJkNm).
**[[utopian-moderator]](https://utopian.io/moderators)**
👍  , ,
properties (23)
authoremrebeyler
permlinkre-steempytutorials-part-6-how-to-automatically-reply-to-mentions-using-steem-python-20180117t211939280z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-01-17 21:19:42
last_update2018-01-17 21:19:42
depth1
children3
last_payout2018-01-24 21:19:42
cashout_time1969-12-31 23:59:59
total_payout_value0.099 HBD
curator_payout_value0.013 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length867
author_reputation448,535,049,068,622
root_title"Part 6: How To Automatically Reply To Mentions Using Steem-Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id30,257,288
net_rshares13,910,433,501
author_curate_reward""
vote details (3)
@amosbastian · (edited)
Thanks! Regarding the node issue, in part 1 of the series @juliank made sure to mention the default node was deprecated and to set a new one using `steempy set nodes https://rpc.steemviz.com` for example. About the mentions, I never realised that! Funny thing is my mind jumped to regex, because I think I recalled that you used it for the mentions on steem.rocks. Guess I learned something today as well, so thanks for that! &#128516;
properties (22)
authoramosbastian
permlinkre-emrebeyler-re-steempytutorials-part-6-how-to-automatically-reply-to-mentions-using-steem-python-20180117t215223506z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["juliank"],"app":"steemit/0.1"}
created2018-01-17 21:52:24
last_update2018-01-17 21:56:06
depth2
children2
last_payout2018-01-24 21:52:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length435
author_reputation174,473,586,900,705
root_title"Part 6: How To Automatically Reply To Mentions Using Steem-Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id30,262,010
net_rshares0
@emrebeyler ·
$0.05
Yeah, actually I wasn't aware of that and the regex pattern is still in place at steem.rocks. @favcau  warned me lately that info can be obtained at json_metadata. :)

Sorry about the node issue, couldn't have time to read the whole series yet.
👍  
properties (23)
authoremrebeyler
permlinkre-amosbastian-re-emrebeyler-re-steempytutorials-part-6-how-to-automatically-reply-to-mentions-using-steem-python-20180117t215427373z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["favcau"],"app":"steemit/0.1"}
created2018-01-17 21:54:27
last_update2018-01-17 21:54:27
depth3
children1
last_payout2018-01-24 21:54:27
cashout_time1969-12-31 23:59:59
total_payout_value0.038 HBD
curator_payout_value0.008 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length244
author_reputation448,535,049,068,622
root_title"Part 6: How To Automatically Reply To Mentions Using Steem-Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id30,262,273
net_rshares6,102,549,028
author_curate_reward""
vote details (1)
@kirkins ·
I'm wondering about the line:

    steem = Steem()

When I look at the github source it's defined on line 13 yet it is never used.

Can that line just be removed?

Also I'm trying to figure out the node error issue. I was able to solve in on another one of your tutorial by passing my keys into the Steem object:

    steem = Steem(nodes,keys)

I'm doing the same with this example but I still get an error about the nodes:
````
WARNING:urllib3.connectionpool:Retrying (Retry(total=17, connect=None, read=None, redirect=0, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f4483e929b0>: Failed to establish a new connection: [Errno -5] No address associated with hostname',)': /
WARNING:urllib3.connectionpool:Retrying (Retry(total=16, connect=None, read=None, redirect=0, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f4483e92ac8>: Failed to establish a new connection: [Errno -5] No address associated with hostname',)': /
WARNING:urllib3.connectionpool:Retrying (Retry(total=15, connect=None, read=None, redirect=0, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f4483e92ba8>: Failed to establish a new connection: [Errno -5] No address associated with hostname',)': /
WARNING:urllib3.connectionpool:Retrying (Retry(total=14, connect=None, read=None, redirect=0, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f4483e92cf8>: Failed to establish a new connection: [Errno -5] No address associated with hostname',)': /
````
Do I have to pass the nodes array into the `blockchain` object too?
properties (22)
authorkirkins
permlinkre-steempytutorials-part-6-how-to-automatically-reply-to-mentions-using-steem-python-20180204t003152306z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-02-04 00:31:54
last_update2018-02-04 00:31:54
depth1
children2
last_payout2018-02-11 00:31:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,777
author_reputation40,750,987,805,431
root_title"Part 6: How To Automatically Reply To Mentions Using Steem-Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id34,762,674
net_rshares0
@kirkins · (edited)
I'm a little further now but I keep getting:

    AccountDoesNotExistsException()

When the script runs `post.reply`.
properties (22)
authorkirkins
permlinkre-kirkins-re-steempytutorials-part-6-how-to-automatically-reply-to-mentions-using-steem-python-20180204t021139608z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"busy","app":"busy/2.3.0"}
created2018-02-04 02:11:39
last_update2018-02-04 03:34:12
depth2
children1
last_payout2018-02-11 02:11:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length117
author_reputation40,750,987,805,431
root_title"Part 6: How To Automatically Reply To Mentions Using Steem-Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id34,777,683
net_rshares0
@kirkins ·
I managed to fix it by specifying my username in the post function:

    post.reply(body=comment,author='kirkins')
properties (22)
authorkirkins
permlinkre-kirkins-re-kirkins-re-steempytutorials-part-6-how-to-automatically-reply-to-mentions-using-steem-python-20180204t040845200z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"busy","app":"busy/2.3.0"}
created2018-02-04 04:08:45
last_update2018-02-04 04:08:45
depth3
children0
last_payout2018-02-11 04:08:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length115
author_reputation40,750,987,805,431
root_title"Part 6: How To Automatically Reply To Mentions Using Steem-Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id34,795,698
net_rshares0
@utopian-io ·
### Hey @steempytutorials I am @utopian-io. I have just upvoted you!
#### Achievements
- You have less than 500 followers. Just gave you a gift to help you succeed!
- Seems like you contribute quite often. AMAZING!
#### Suggestions
- Contribute more often to get higher and higher rewards. I wish to see you often!
- Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!
#### Get Noticed!
- Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!
#### Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. <a href="https://discord.gg/zTrEMqB">Participate on Discord</a>. Lets GROW TOGETHER!
- <a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for my Witness With SteemConnect</a>
- <a href="https://v2.steemconnect.com/sign/account-witness-proxy?proxy=utopian-io&approve=1">Proxy vote to Utopian Witness with SteemConnect</a>
- Or vote/proxy on <a href="https://steemit.com/~witnesses">Steemit Witnesses</a>

[![mooncryption-utopian-witness-gif](https://steemitimages.com/DQmYPUuQRptAqNBCQRwQjKWAqWU3zJkL3RXVUtEKVury8up/mooncryption-s-utopian-io-witness-gif.gif)](https://steemit.com/~witnesses)

**Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x**
properties (22)
authorutopian-io
permlinkre-steempytutorials-part-6-how-to-automatically-reply-to-mentions-using-steem-python-20180118t170709504z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-01-18 17:07:12
last_update2018-01-18 17:07:12
depth1
children0
last_payout2018-01-25 17:07:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,514
author_reputation152,955,367,999,756
root_title"Part 6: How To Automatically Reply To Mentions Using Steem-Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id30,438,005
net_rshares0