Create crypto sentiment bot
Tags: #telegram #sentiment #bot #naas_drivers #ai
This notebook is a demo of how you can use naas drivers and Telegram to create a Crypto sentiment bot. Please note that if you stop the notebook, the bot will not work anymore.

Input

Install packages

1
!pip install python-telegram-bot --user
Copied!

Import libraries

1
import logging
2
from telegram.ext import *
3
import numpy as np
4
from naas_drivers import newsapi
5
from naas_drivers import sentiment
6
from datetime import datetime, timedelta
Copied!

Variables

1
TELEGRAM_API_KEY = "***********"
Copied!
1
NEWSAPI_API_KEY = "***********"
Copied!
1
# Set up the logging
2
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
3
logging.info('Starting Bot...')
Copied!

Get last 24 hours articles from NewsAPI on a CoinMarketCap top coins

1
#parameters for newsapi
2
FROM_DATE = (datetime.now()-timedelta(days=1)).replace(microsecond=0).isoformat()
3
TO_DATE = datetime.now().replace(microsecond=0).isoformat()
4
5
#top marketcap coins according to coinmarketcap
6
coins= ["bitcoin","ethereum", "ripple","dogecoin","cardano",
7
"polygon","binance","polkadot","uniswap","litecoin",
8
"chainlink","solana","stellar"]
9
10
#connect to Newsapi Naas drivers
11
newsapi.connect(NEWSAPI_API_KEY)
12
newsapi.connect()
Copied!

Model

User need to ask for coins ticker and get responses

1
#user_response
2
def get_response(user_message):
3
4
usr_msg_text = user_message.lower()
5
6
if usr_msg_text in coins: #check if returned message has the top coins
7
data = newsapi.get(q=usr_msg_text,
8
from_param=FROM_DATE,
9
to = TO_DATE,
10
language ="en")
11
if len(data)==0:#extra check to returned data
12
sentiment = "No news for this ticker in last 24 hours, try another"
13
return sentiment
14
else:
15
sentiment_df = sentiment.get(data, column_name="title")#sentiment calculation
16
sentiment = sentiment_df["Score"].mean()
17
else:
18
sentiment = 'There is no data for this ticker\n use \help command'
19
20
return sentiment
Copied!

Here are the commands to communicate with Telegram

1
#commands
2
def start_command(update, context):
3
update.message.reply_text('''Hello there! I\'m a crypto sentiment bot.
4
Send me the coin name, I\'ll send you sentiment!''')
5
6
7
def help_command(update, context):
8
update.message.reply_text('''check the coin names from the list below!
9
bitcoin\n etherium\n ripple\n dogecoin\n cardano\n polygon
10
binance\n polkadot\n uniswap\n litecoin\n chainlink\n solana\n stellar''')
11
12
#message handler
13
def handle_message(update, context):
14
text = str(update.message.text).lower()
15
logging.info(f'User ({update.message.chat.id}) says: {text}')
16
17
# Bot response
18
sentiment_naas = get_response(text)
19
update.message.reply_text(sentiment_naas)
20
21
#error logs
22
def error(update, context):
23
# Logs errors
24
logging.error(f'Update {update} caused error {context.error}')
Copied!

Output

Start the bot

1
# Run the programme
2
3
# create an object "bot"
4
updater = Updater(TELEGRAM_API_KEY, use_context=True)
5
dp = updater.dispatcher
6
7
# bot's command handlers
8
dp.add_handler(CommandHandler('start', start_command))
9
dp.add_handler(CommandHandler('help', help_command))
10
11
# bot's text handlers
12
dp.add_handler(MessageHandler(Filters.text, handle_message))
13
14
# bot's error handler
15
dp.add_error_handler(error)
16
17
18
# Run the bot
19
updater.start_polling(1.0)
20
updater.idle()
Copied!
Info: the cell above will stay alive until you press stop, the bot will not respond anymore once the cell is stoped.
Last modified 2mo ago
Copy link
Edit on GitHub