1
0
mirror of https://gitlab.com/simple-stock-bots/simple-stock-bot.git synced 2025-07-25 23:51:41 +00:00

moved files for telegram bot into thier own folder

This commit is contained in:
2019-02-05 17:02:43 -07:00
parent 3764f5f2a6
commit b3d83a72b4
5 changed files with 2 additions and 2 deletions

8
bot/Dockerfile Normal file
View File

@@ -0,0 +1,8 @@
FROM python:3.7-slim
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD [ "python", "./stockBot.py" ]

7
bot/credentials.py Normal file
View File

@@ -0,0 +1,7 @@
secrets = {
"TELEGRAM_TOKEN": "TELEGRAM BOT TOKEN HERE",
"TWITTER_CONSUMER_API": "CONSUMER_API",
"TWITTER_CONSUMER_SECRET": "CONSUMER_SECRET",
"TWITTER_ACCESS_TOKEN": "ACCESS_TOKEN",
"TWITTER_ACCESS_SECRET": "ACCESS_SECRET",
}

2
bot/requirements.txt Normal file
View File

@@ -0,0 +1,2 @@
telegram==0.0.1
python-telegram-bot==11.1.0

176
bot/stockBot.py Normal file
View File

@@ -0,0 +1,176 @@
# Work with Python 3.7
import json
import logging
import re
import urllib.request
import telegram
from telegram.ext import CommandHandler, Filters, MessageHandler, Updater
import credentials
import tickerInfo
TOKEN = credentials.secrets["TELEGRAM_TOKEN"]
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
print("Bot Online")
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
"""Send a message when the command /start is issued."""
update.message.reply_text("I am started and ready to go!")
def help(bot, update):
"""Send a message when the command /help is issued."""
update.message.reply_text("I don't know how to help yet!")
def news(bot, update):
"""Send a message when the /news command is issued."""
message = update.message.text
chat_id = update.message.chat_id
try:
# regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters
tickers = re.findall("[$](\w{1,4})", message)
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
## Checks if a ticker was passed in
if tickers == []:
update.message.reply_text(
"Please type a ticker after your command with a dollar sign: /news $tsla"
)
else:
tickerData = tickerInfo.tickerQuote(tickers)
for ticker in tickers:
ticker = ticker.upper()
# Makes sure ticker exists
if tickerData[ticker] == 1:
name = tickerData[ticker + "Name"]
price = tickerData[ticker + "Price"]
change = tickerData[ticker + "Change"]
message = (
"The current stock price of "
+ name
+ " is $**"
+ str(price)
+ "**"
)
if change > 0:
message = (
message
+ ", the stock is currently **up "
+ str(change)
+ "%**"
)
elif change < 0:
message = (
message
+ ", the stock is currently **down"
+ str(change)
+ "%**"
)
else:
message = (
message + ", the stock hasn't shown any movement today."
)
news = tickerInfo.stockNewsList(ticker)
for source in news:
message = message + "\n[" + source + "](" + news[source] + ")"
update.message.reply_text(
text=message, parse_mode=telegram.ParseMode.MARKDOWN
)
else:
update.message.reply_text(ticker + " Does not exist.")
except:
pass
def stockInfo(bot, update):
message = update.message.text
chat_id = update.message.chat_id
try:
# regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters
tickers = re.findall("[$](\w{1,4})", message)
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
tickerData = tickerInfo.tickerQuote(tickers)
for ticker in tickers:
ticker = ticker.upper()
# Makes sure ticker exists
if tickerData[ticker] == 1:
name = tickerData[ticker + "Name"]
price = tickerData[ticker + "Price"]
change = tickerData[ticker + "Change"]
message = (
"The current stock price of " + name + " is $**" + str(price) + "**"
)
if change > 0:
message = (
message + ", the stock is currently **up " + str(change) + "%**"
)
elif change < 0:
message = (
message
+ ", the stock is currently **down "
+ str(change)
+ "%**"
)
else:
message = message + ", the stock hasn't shown any movement today."
update.message.reply_text(
text=message, parse_mode=telegram.ParseMode.MARKDOWN
)
else:
update.message.reply_text(ticker + " Does not exist.")
except:
pass
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
updater = Updater(TOKEN)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("news", news))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, stockInfo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == "__main__":
main()

54
bot/tickerInfo.py Normal file
View File

@@ -0,0 +1,54 @@
import urllib.request
import json
def tickerQuote(tickers):
"""Gathers information from IEX api on stock"""
stockData = {}
IEXURL = (
"https://api.iextrading.com/1.0/stock/market/batch?symbols="
+ ",".join(tickers)
+ "&types=quote"
)
print("Gathering Quote from " + IEXURL)
with urllib.request.urlopen(IEXURL) as url:
IEXData = json.loads(url.read().decode())
for ticker in tickers:
ticker = ticker.upper()
# Makes sure ticker exists before populating a dictionary
if ticker in IEXData:
stockData[ticker] = 1
stockData[ticker + "Name"] = IEXData[ticker]["quote"]["companyName"]
stockData[ticker + "Price"] = IEXData[ticker]["quote"]["latestPrice"]
stockData[ticker + "Change"] = round(
(IEXData[ticker]["quote"]["changePercent"] * 100), 2
)
stockData[ticker + "Image"] = stockLogo(ticker)
print(ticker + " Quote Gathered")
else:
stockData[ticker] = 0
return stockData
def stockNewsList(ticker):
"""Makes a bunch of strings that are links to news websites for an input ticker"""
print("Gather News on " + ticker)
news = {
"Bravos": "https://bravos.co/" + ticker,
"Seeking Alpha": "https://seekingalpha.com/symbol/" + ticker,
"MSN Money": "https://www.msn.com/en-us/money/stockdetails?symbol=" + ticker,
"Yahoo Finance": "https://finance.yahoo.com/quote/" + ticker,
"Wall Street Journal": "https://quotes.wsj.com/" + ticker,
"The Street": "https://www.thestreet.com/quote/" + ticker + ".html",
"Zacks": "https://www.zacks.com/stock/quote/" + ticker,
}
print("News gathered.")
return news
def stockLogo(ticker):
"""returns a png of an input ticker"""
logoURL = "https://g.foolcdn.com/art/companylogos/mark/" + ticker + ".png"
return logoURL