Hi all, I've been writing a simple telegram bot to extract stock info in Vietnam. It works properly on my computer. But when I tried running this on pythonanywhere, the bot is still running okay, but no matter how I send the command, it would return the error message that I preset ("Error retrieving information for {ticker}. Please check the ticker and try again.").
I inserted the logging and it seems the external module that I'm using (vnstock) is trying to access this API apipubaws.tcbs.com.vn:443. I've seen a similar question here https://www.pythonanywhere.com/forums/topic/27748/, and I'm guessing my issue is similar, where the API is not accessible with my free account.
Can someone help me to see if it's really the issue here? And if it is, how can I solve it? Big thanks.
Please see an extract of my code below:
from vnstock import *
import datetime
from datetime import date, timedelta, datetime, time
import logging
import telegram
from telegram.ext import *
from queue import Queue
API_KEY = '6061983614:AAEiElhVxoAMy3s4rz6S187iLeLgSLGmDnQ'
#Set up logging:
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logging.info('Bot started ...')
# Define a function to handle the /sum command
async def sum_command(update, context):
ticker = context.args[0].upper() # Get the stock ticker from user input
try:
#today = datetime.datetime.now().strftime('%Y-%m-%d')
today = datetime.now() # Get today's date AND TIME
# If today is weekday and the current time is before 9:15 AM, get yesterday's date
if today.weekday() < 5 and today.time() < time(9, 15):
last_trading_day = today - timedelta(days=1)
elif today.weekday() == 6: # If today is Sunday, get last Friday
last_trading_day = today - timedelta(days=2)
elif today.weekday() == 5: # If today is Saturday, get last Friday
last_trading_day = today - timedelta(days=1)
# Otherwise, get today
else:
last_trading_day = today - timedelta(days=0)
T_0 = last_trading_day.strftime('%Y-%m-%d')
#define last_trading_day()[1] aka T-1
if last_trading_day.weekday() == 0: # If last trading day is Monday, get last Friday
start_date = last_trading_day - timedelta(days = 4)
else: # Otherwise, get last trading day minus one
start_date = last_trading_day - timedelta(days = 2)
T_minus_2 = start_date.strftime('%Y-%m-%d')
# Get the stock data:
stock_data = stock_historical_data(ticker, T_minus_2, T_0)
price = stock_data.iloc[1, 3]
vol = stock_data.iloc[1, 4]
high = stock_data.iloc[1, 1]
low = stock_data.iloc[1, 2]
close_prev = stock_data.iloc[0,3]
price_change = price - close_prev
perc_change = (price_change / close_prev)*100
price_change = round(price_change,0)
perc_change = round(perc_change,2)
if price_change >0:
price_change_str = f'+{price_change:,.0f}'
perc_change_str = f'+{perc_change:,.2f}'
else:
price_change_str = f'{price_change:,.0f}'
perc_change_str = f'{perc_change:,.2f}'
price_str = f'{price:,.0f}'
vol_str = f'{vol:,.0f}'
high_str = f'{high:,.0f}'
low_str = f'{low:,.0f}'
message = f"Info for {ticker}:\n"
message += f"P: {price_str}\n"
message += f"△: {price_change_str} , {perc_change_str}%\n"
message += f"H: {high_str}\n"
message += f"L: {low_str}\n"
message += f"Vol: {vol_str}\n"
await update.message.reply_text(text=message)
except:
await update.message.reply_text(text=f"Error retrieving information for {ticker}. Please check the ticker and try again.")
def main() -> None:
"""Run the bot."""
# Create the Application and pass it your bot's token.
application = Application.builder().token(API_KEY).build()
# Register the commands...
application.add_handler(CommandHandler("help", help_command))
application.add_handler(CommandHandler("sum", sum_command))
# Run the bot
application.run_polling()
if __name__ == "__main__":
main()