<p dir="auto">This tutorial is part of a series where we explain different aspects of programming with <code>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 <code>steem-python!
<hr />
<h4>What will I learn
<ul>
<li>How to create a regular expression
<li>How to find people mentioning you
<li>How to reply to them
<h4>Requirements
<ul>
<li>Python3.6
<li><code>steem-python
<li><code>re
<h4>Difficulty
<ul>
<li>Basic
<hr />
<h3>Tutorial
<h4>Streaming the blockchain for mentions
<p dir="auto">We have already gone over how to stream the blockchain in <a href="https://utopian.io/utopian-io/@steempytutorials/part-2-how-to-stream-and-filter-the-blockchain-using-steem-python" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">part 2 of this tutorial series, 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
<pre><code>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
<h4>Creating a regular expression
<p dir="auto">To find out who mentions us we should read the body of each post and find out if it contains <code>@username. A great way to do this is by using a <a href="https://docs.python.org/3/howto/regex.html" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">regular expression. 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 <a href="https://stackoverflow.com/questions/2304632/regex-for-twitter-username" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">here
<pre><code>(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9]+)
<p dir="auto">We can then use the function <code>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
<pre><code>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)
<p dir="auto">which outputs
<pre><code>['amosbastian', 'juliank', 'steempytutorials']
<h4>Mentions on the blockchain
<p dir="auto">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
<pre><code>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
<p dir="auto">Running this program and testing it showed the following
<pre><code>$ python mentions.py
amosbastian just mentioned you!
<h4>Replying to mentions
<p dir="auto">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 <code>reply() function, which makes replying to a post very simple! Instead of printing the post we will change it to
<pre><code>post.reply(f"Hey @{post['author']} thanks for mentioning me!")
<p dir="auto">and indeed, it works as expected
<p dir="auto"><center><img src="https://images.hive.blog/768x0/https://res.cloudinary.com/hpiynhbhq/image/upload/v1516212007/vxg8yhopctfrorjtrvtx.png" alt="reply_mention.png" srcset="https://images.hive.blog/768x0/https://res.cloudinary.com/hpiynhbhq/image/upload/v1516212007/vxg8yhopctfrorjtrvtx.png 1x, https://images.hive.blog/1536x0/https://res.cloudinary.com/hpiynhbhq/image/upload/v1516212007/vxg8yhopctfrorjtrvtx.png 2x" />
<p dir="auto"><strong>Congratulations, you can now automatically reply to anyone who mentions you using <code>steem-python!
<h4>Curriculum
<ul>
<li><a href="https://utopian.io/utopian-io/@amosbastian/how-to-install-steem-python-the-official-steem-library-for-python" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 0: How To Install Steem-python, The Official Steem Library For Python
<li><a href="https://utopian.io/utopian-io/@steempytutorials/part-1-how-to-configure-the-steempy-cli-wallet-and-upvote-an-article-with-steem-python" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 1: How To Configure The Steempy CLI Wallet And Upvote An Article With Steem-Python
<li><a href="https://utopian.io/utopian-io/@steempytutorials/part-2-how-to-stream-and-filter-the-blockchain-using-steem-python" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 2: How To Stream And Filter The Blockchain Using Steem-Python
<li><a href="https://steemit.com/utopian-io/@steempytutorials/part-3-creating-a-dynamic-upvote-bot-that-runs-24-7-first-weekly-challenge-3-steem-prize-pool" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 3: Creating A Dynamic Upvote Bot That Runs 24/7
<li><a href="https://utopian.io/utopian-io/@steempytutorials/part-4-how-to-follow-a-voting-trail-using-steem-python" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 4: How To Follow A Voting Trail Using Steem-Python
<li><a href="https://utopian.io/utopian-io/@steempytutorials/part-5-post-an-article-directly-to-the-steem-blockchain-and-automatically-buy-upvotes-from-upvote-bots" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 5: Post An Article Directly To The Steem Blockchain And Automatically Buy Upvotes From Upvote Bots
<hr />
<p dir="auto">The code for this tutorial can be found on <a href="https://github.com/amosbastian/steempy-tutorials/blob/master/part_6/mentions.py" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">GitHub!
<p dir="auto"><span>This tutorial was written by <a href="/@amosbastian">@amosbastian in conjunction with <a href="/@juliank">@juliank.
<p dir="auto"><br /><hr /><em>Posted on <a href="https://utopian.io/utopian-io/@steempytutorials/part-6-how-to-automatically-reply-to-mentions-using-steem-python" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Utopian.io - Rewarding Open Source Contributors<hr /><p>
Thank you for the contribution. It has been approved.
<p dir="auto">Btw, I have a couple of ideas about this post: <p dir="auto"><strong>Node issue <p dir="auto"><code>stream = map(Post, blockchain.stream(filter_by=["comment"])) <p dir="auto">This shouldn't work since default node defined at steem-python is <em>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. <p dir="auto"><strong>Mentions <p dir="auto">We can use <code>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? <p dir="auto">Great job on the series! Looking forward to see more. <p dir="auto">You can contact us on <a href="https://discord.gg/uTyJkNm" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Discord.<br /> <strong><a href="https://utopian.io/moderators" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">[utopian-moderator]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! 😄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 usingYeah, 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.
Haha, no worries, I had to go to part 1 myself and check if @juliank had actually mentioned it.
Hey @steempytutorials I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
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
I'm wondering about the line:
<pre><code>steem = Steem() <p dir="auto">When I look at the github source it's defined on line 13 yet it is never used. <p dir="auto">Can that line just be removed? <p dir="auto">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: <pre><code>steem = Steem(nodes,keys) <p dir="auto">I'm doing the same with this example but I still get an error about the nodes: <pre><code>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',)': / <p dir="auto">Do I have to pass the nodes array into the <code>blockchain object too?I'm a little further now but I keep getting:
<pre><code>AccountDoesNotExistsException() <p dir="auto">When the script runs <code>post.reply.I managed to fix it by specifying my username in the post function:
<pre><code>post.reply(body=comment,author='kirkins')