Simple Transaction Monitor
# Pretty straight forward monitor
I'm back again with another simple python snippet of code to use in future projects. A lot of projects begin as needing something to monitor the chain and react accordingly. I thought about this and decided the best example to show how simple it is and a teaching tool to myself was to monitor the transaction ops and insert them into a database if they were to or from me.
![monitor_output.png](https://files.peakd.com/file/peakd-hive/thecrazygm/tr5VEsVA-monitor_output.png)
This is the basis of listening for memos to react with a response of sorts. (In this case, put them into a simple sqlite3 DB) another popular option is to listen for the `comments` op and check if something is mentioned (that may be another project/lesson in the future)
![monitor_db_output.png](https://files.peakd.com/file/peakd-hive/thecrazygm/fG2RgesY-monitor_db_output.png)
This example requires both [beem](https://beem.readthedocs.io/en/latest/index.html) and [dataset](https://dataset.readthedocs.io/en/latest/index.html) and will watch for whatever account you set as the `watch` variable.
```python
#!/usr/bin/env python3
import dataset
from beem import Steem
from beem.blockchain import Blockchain
watch = "thecrazygm"
hive = Steem(node='https://anyx.io')
db = dataset.connect('sqlite:///mydatabase.db')
# System Variables
blockchain = Blockchain(steem_instance=hive)
stream = blockchain.stream(opNames=['transfer'], raw_ops=False, threading=True, thread_num=4)
table = db[watch]
# parse json data to SQL insert
def update_db(post):
try:
table.insert(dict(post))
db.commit()
except Exception as e:
print(f'[Error: {e} moving on]')
db.rollback()
def monitor():
print("[Starting up...]")
db.begin()
# Read the live stream and filter out only transfers
for post in stream:
if post["to"] == watch or post["from"] == watch:
print(f"[Transaction Found from {post['from']} to {post['to']}]")
update_db(post)
if __name__ == "__main__":
monitor()
```
The code can be found always up to date at my [GitHub gist area](https://gist.github.com/TheCrazyGM) at this file: [monitor.py](https://gist.github.com/TheCrazyGM/9b2882a4adcea826815489b5a00ed089)
If you like what I'm doing consider following me, either here or on [GitHub](https://github.com/thecrazygm) or buy me a coffee.
Again, stay safe out there people,
Michael Garcia a.k.a. @TheCrazyGM
![](https://files.peakd.com/file/peakd-hive/thecrazygm/LjWZDEWC-signature_fancy.png)