diff --git a/HTS_Alert.py b/HTS_Alert.py index ab30c60..6542b9a 100644 --- a/HTS_Alert.py +++ b/HTS_Alert.py @@ -2,13 +2,13 @@ import time import requests from bs4 import BeautifulSoup from datetime import datetime -from stock.util.SlackBot import SlackBot +from stock.util.TelegramBot import TelegramBot class HTS_Alert : - slackBot = None + bot = None def __init__(self): - self.slackBot = SlackBot() + self.bot = TelegramBot() return def checkPrice(self, code): @@ -29,7 +29,7 @@ class HTS_Alert : c_price = int(arr[1].replace(',', '')) if c_price < CHECK_PRICE[code_index]: - self.slackBot.sendMsg(code + " " + str(CHECK_PRICE[code_index]) + " " + PERCENT[code_index] + "를 파세요...") + self.bot.sendMsg(code + " " + str(CHECK_PRICE[code_index]) + " " + PERCENT[code_index] + "를 파세요...") code_index += 1 if code_index > len(CHECK_PRICE): diff --git a/HTS_etf.py b/HTS_etf.py index f12c69f..92c5b4e 100644 --- a/HTS_etf.py +++ b/HTS_etf.py @@ -9,7 +9,7 @@ from hts.OrderType import OrderType from hts.BuySellChecker import BuySellChecker from hts.OrderChecker import OrderChecker from stock.util.LabelChecker import LabelChecker -from stock.util.SlackBot import SlackBot +from stock.util.TelegramBot import TelegramBot from stock.analysis.StockStatus import StockStatus @@ -22,7 +22,7 @@ class HTS_etf(HTS): orderChecker = None buySellChecker = None labelChecker = None - slackBot = None + bot = None stockStatus = None def __init__(self, RESOURCE_PATH, stock_code, stock_name, SELL_GAP): @@ -36,7 +36,7 @@ class HTS_etf(HTS): self.orderChecker = OrderChecker(self.RESOURCE_PATH, self.stock_code) self.buySellChecker = BuySellChecker() self.labelChecker = LabelChecker(RESOURCE_PATH) - self.slackBot = SlackBot() + self.bot = TelegramBot() self.stockStatus = StockStatus(RESOURCE_PATH) return @@ -132,7 +132,7 @@ class HTS_etf(HTS): def buyRealTime(self, today, analyzed_day=1000, MAX_PRICE=10000, logFp=None): rsi = self.getTodayRSI() if rsi > 79: - self.slackBot.sendMsg("exit... {} ({}) RSI: {}".format(self.stock_code, self.stock_name, rsi)) + self.bot.sendMsg("exit... {} ({}) RSI: {}".format(self.stock_code, self.stock_name, rsi)) return print("START...") @@ -142,9 +142,9 @@ class HTS_etf(HTS): while datetime.strptime(today + " 063000", '%Y%m%d %H%M%S') < THIS_TIME < datetime.strptime(today + " 153100",'%Y%m%d %H%M%S'): if THIS_TIME < datetime.strptime(today + " 085500", '%Y%m%d %H%M%S'): - self.slackBot.sendMsg("WAIT... {} ({}) RSI: {}".format(self.stock_code, self.stock_name, rsi)) + self.bot.sendMsg("WAIT... {} ({}) RSI: {}".format(self.stock_code, self.stock_name, rsi)) if datetime.strptime(today + " 090000", '%Y%m%d %H%M%S') < THIS_TIME < datetime.strptime(today + " 090100", '%Y%m%d %H%M%S'): - self.slackBot.sendMsg("START... {} ({}) RSI: {}".format(self.stock_code, self.stock_name, rsi)) + self.bot.sendMsg("START... {} ({}) RSI: {}".format(self.stock_code, self.stock_name, rsi)) logFp.write("START {} ({}) RSI: {}\n".format(self.stock_code, self.stock_name, rsi)) if datetime.strptime(today + " 090000", '%Y%m%d %H%M%S') < THIS_TIME < datetime.strptime(today + " 151500", '%Y%m%d %H%M%S'): @@ -205,7 +205,7 @@ class HTS_etf(HTS): (str(THIS_TIME), self.stock_code, bs_buy_price, bs_sell_price, data["open"][len(data["open"])-1], data["close"][len(data["close"])-1], data["high"][len(data["high"])-1], data["low"][len(data["low"])-1], data["macd"][len(data["macd"])-1])) if (int(THIS_TIME.strftime("%M")) % 50 == 0 or int(THIS_TIME.strftime("%M")) % 20 == 0): - self.slackBot.post_live_to_slack(self.stock_code, self.stock_name, data["close"][len(data["close"])-1], data["macd"][len(data["macd"])-1]) + self.bot.alarm_live(self.stock_code, self.stock_name, data["close"][len(data["close"])-1], data["macd"][len(data["macd"])-1]) logFp.flush() time.sleep(60) diff --git a/HTS_etf_122630.py b/HTS_etf_122630.py index 260fd2d..cbdfc5f 100644 --- a/HTS_etf_122630.py +++ b/HTS_etf_122630.py @@ -27,5 +27,5 @@ if __name__ == "__main__": hts.insertStockData(today, stock_code, stock_name) hts.disconnect() - hts.slackBot.sendMsg("done... {} ({})".format(stock_code, stock_name)) + hts.bot.sendMsg("done... {} ({})".format(stock_code, stock_name)) print("done...") \ No newline at end of file diff --git a/HTS_etf_233740.py b/HTS_etf_233740.py index 4600683..17087a5 100644 --- a/HTS_etf_233740.py +++ b/HTS_etf_233740.py @@ -27,5 +27,5 @@ if __name__ == "__main__": hts.insertStockData(today, stock_code, stock_name) hts.disconnect() - hts.slackBot.sendMsg("done... {} ({})".format(stock_code, stock_name)) + hts.bot.sendMsg("done... {} ({})".format(stock_code, stock_name)) print("done...") \ No newline at end of file diff --git a/HTS_etf_251340.py b/HTS_etf_251340.py index 4ffb503..94ee463 100644 --- a/HTS_etf_251340.py +++ b/HTS_etf_251340.py @@ -27,5 +27,5 @@ if __name__ == "__main__": hts.insertStockData(today, stock_code, stock_name) hts.disconnect() - hts.slackBot.sendMsg("done... {} ({})".format(stock_code, stock_name)) + hts.bot.sendMsg("done... {} ({})".format(stock_code, stock_name)) print("done...") \ No newline at end of file diff --git a/HTS_etf_252670.py b/HTS_etf_252670.py index b278c79..0af6348 100644 --- a/HTS_etf_252670.py +++ b/HTS_etf_252670.py @@ -27,5 +27,5 @@ if __name__ == "__main__": hts.insertStockData(today, stock_code, stock_name) hts.disconnect() - hts.slackBot.sendMsg("done... {} ({})".format(stock_code, stock_name)) + hts.bot.sendMsg("done... {} ({})".format(stock_code, stock_name)) print("done...") \ No newline at end of file diff --git a/HTS_etf_long.py b/HTS_etf_long.py index 49b8c46..c6ecb51 100644 --- a/HTS_etf_long.py +++ b/HTS_etf_long.py @@ -10,7 +10,7 @@ from hts.OrderType import OrderType from hts.BuySellChecker import BuySellChecker from hts.OrderChecker import OrderChecker from stock.util.LabelChecker import LabelChecker -from stock.util.SlackBot import SlackBot +from stock.util.TelegramBot import TelegramBot from stock.analysis.StockStatus import StockStatus class HTS_etf (HTS): @@ -21,7 +21,7 @@ class HTS_etf (HTS): orderChecker = None buySellChecker = None labelChecker = None - slackBot = None + bot = None stockStatus = None def __init__(self, RESOURCE_PATH): @@ -32,7 +32,7 @@ class HTS_etf (HTS): self.orderChecker = OrderChecker(self.RESOURCE_PATH, "ETF") self.buySellChecker = BuySellChecker() self.labelChecker = LabelChecker(RESOURCE_PATH) - self.slackBot = SlackBot() + self.bot = TelegramBot() self.stockStatus = StockStatus(RESOURCE_PATH) return @@ -60,7 +60,7 @@ class HTS_etf (HTS): if jangoDic[code]['매도가능'] > 0: if 2 < jangoDic[code]['평가손익']: self.requestOrder(OrderType.sell, code[1:], jangoDic[code]['매도가능'], bs_sell_price) - self.slackBot.post_to_slack(code, jangoDic[code]['종목명'], "SELL", bs_sell_price, jangoDic[code]['매도가능']) + self.bot.post(code, jangoDic[code]['종목명'], "SELL", bs_sell_price, jangoDic[code]['매도가능']) check = True else: continue @@ -70,7 +70,7 @@ class HTS_etf (HTS): # 3% 이상 시 수익 매도 currentStock = self.currentStock(code[1:]) self.requestOrder(OrderType.sell, code[1:], jangoDic[code]['매도가능'], currentStock['close']) - self.slackBot.post_to_slack(code, jangoDic[code]['종목명'], "SELL", currentStock['close'], jangoDic[code]['매도가능']) + self.bot.post(code, jangoDic[code]['종목명'], "SELL", currentStock['close'], jangoDic[code]['매도가능']) check = True return check @@ -281,8 +281,8 @@ class HTS_etf (HTS): orderNum = self.requestOrder(OrderType.buy, stock['stock_code'], buy_count , bs_buy_price) self.orderChecker.buy(today, "A" + stock['stock_code'], buy_count, bs_buy_price, orderNum) - # slackbot에 메시지를 보냄 - self.slackBot.post_to_slack(stock['stock_code'], stock['stock_name'], "BUY", bs_buy_price, buy_count) + # bot에 메시지를 보냄 + self.bot.post(stock['stock_code'], stock['stock_name'], "BUY", bs_buy_price, buy_count) # 로그 출력 print("BUY", THIS_TIME.strftime('%Y%m%d %H%M%S'), orderNum, stock['stock_code'], stock['stock_name'], bs_buy_price, buy_count) diff --git a/HTS_etf_short.py b/HTS_etf_short.py index 74eee50..3da149d 100644 --- a/HTS_etf_short.py +++ b/HTS_etf_short.py @@ -10,7 +10,7 @@ from hts.OrderType import OrderType from hts.BuySellChecker import BuySellChecker from hts.OrderChecker import OrderChecker from stock.util.LabelChecker import LabelChecker -from stock.util.SlackBot import SlackBot +from stock.util.TelegramBot import TelegramBot from stock.analysis.StockStatus import StockStatus class HTS_etf (HTS): @@ -21,7 +21,7 @@ class HTS_etf (HTS): orderChecker = None buySellChecker = None labelChecker = None - slackBot = None + bot = None stockStatus = None def __init__(self, RESOURCE_PATH): @@ -32,7 +32,7 @@ class HTS_etf (HTS): self.orderChecker = OrderChecker(self.RESOURCE_PATH, "ETF") self.buySellChecker = BuySellChecker() self.labelChecker = LabelChecker(RESOURCE_PATH) - self.slackBot = SlackBot() + self.bot = TelegramBot() self.stockStatus = StockStatus(RESOURCE_PATH) return @@ -60,7 +60,7 @@ class HTS_etf (HTS): if jangoDic[code]['매도가능'] > 0: if 2 < jangoDic[code]['평가손익']: self.requestOrder(OrderType.sell, code[1:], jangoDic[code]['매도가능'], bs_sell_price) - self.slackBot.post_to_slack(code, jangoDic[code]['종목명'], "SELL", bs_sell_price, jangoDic[code]['매도가능']) + self.bot.post(code, jangoDic[code]['종목명'], "SELL", bs_sell_price, jangoDic[code]['매도가능']) check = True else: continue @@ -70,7 +70,7 @@ class HTS_etf (HTS): # 3% 이상 시 수익 매도 currentStock = self.currentStock(code[1:]) self.requestOrder(OrderType.sell, code[1:], jangoDic[code]['매도가능'], currentStock['close']) - self.slackBot.post_to_slack(code, jangoDic[code]['종목명'], "SELL", currentStock['close'], jangoDic[code]['매도가능']) + self.bot.post(code, jangoDic[code]['종목명'], "SELL", currentStock['close'], jangoDic[code]['매도가능']) check = True return check @@ -283,8 +283,8 @@ class HTS_etf (HTS): orderNum = self.requestOrder(OrderType.buy, stock['stock_code'], buy_count , bs_buy_price) self.orderChecker.buy(today, "A" + stock['stock_code'], buy_count, bs_buy_price, orderNum) - # slackbot에 메시지를 보냄 - self.slackBot.post_to_slack(stock['stock_code'], stock['stock_name'], "BUY", bs_buy_price, buy_count) + # bot에 메시지를 보냄 + self.bot.post(stock['stock_code'], stock['stock_name'], "BUY", bs_buy_price, buy_count) # 로그 출력 print("BUY", THIS_TIME.strftime('%Y%m%d %H%M%S'), orderNum, stock['stock_code'], stock['stock_name'], bs_buy_price, buy_count) diff --git a/HTS_stocks.py b/HTS_stocks.py index 5654a68..0de42ff 100644 --- a/HTS_stocks.py +++ b/HTS_stocks.py @@ -10,7 +10,7 @@ from hts.OrderType import OrderType from hts.BuySellChecker import BuySellChecker from hts.OrderChecker import OrderChecker -from stock.util.SlackBot import SlackBot +from stock.util.TelegramBot import TelegramBot from stock.analysis.StockStatus import StockStatus class HTS_Stocks (HTS): @@ -19,7 +19,7 @@ class HTS_Stocks (HTS): orderChecker = None buySellChecker = None labelChecker = None - slackBot = None + bot = None stockStatus = None analyzed_day = None MAX_BUY_PRICE = None @@ -29,7 +29,7 @@ class HTS_Stocks (HTS): def __init__(self, RESOURCE_PATH): super().__init__(RESOURCE_PATH) - self.slackBot = SlackBot() + self.bot = TelegramBot() self.RESOURCE_PATH = RESOURCE_PATH self.stockStatus = StockStatus(RESOURCE_PATH) @@ -128,8 +128,8 @@ class HTS_Stocks (HTS): orderNum = self.requestOrder(OrderType.buy, stock_code, buy_count, bs_buy_price) self.orderChecker.buy(today, "A" + stock_code, buy_count, bs_buy_price, orderNum) - # slackbot에 메시지를 보냄 - self.slackBot.post_to_slack(stock_code, stock_name, "BUY", bs_buy_price, buy_count) + # bot에 메시지를 보냄 + self.bot.post(stock_code, stock_name, "BUY", bs_buy_price, buy_count) # 로그 출력 print("BUY", THIS_TIME.strftime('%Y%m%d %H%M%S'), orderNum, stock_code, stock_name, bs_buy_price, buy_count) diff --git a/StockCrawler.py b/StockCrawler.py index 522c405..56da703 100644 --- a/StockCrawler.py +++ b/StockCrawler.py @@ -11,7 +11,7 @@ from stock.crawler.MetaCrawler import MetaCrawler from stock.crawler.StockCrawler import StockCrawler from stock.analysis.AnalyzerSqlite import AnalyzerSqlite from stock.analysis.StockStatus import StockStatus -from stock.util.SlackBot import SlackBot +from stock.util.TelegramBot import TelegramBot today = datetime.now().strftime("%Y-%m-%d") @@ -30,11 +30,11 @@ stockFileName = os.path.join(RESOURCE_PATH, 'stock.db') week = datetime.today().weekday() -slackBot = SlackBot() +bot = TelegramBot() if week in (0, 1, 2, 3, 4): # 0:월, 1:화, 2:수, 3:목, 4:금, 5:토, 6:일 - slackBot.sendMsg("1. start to crawl...") + bot.sendMsg("1. start to crawl...") @@ -63,7 +63,7 @@ if week in (0, 1, 2, 3, 4): # 0:월, 1:화, 2:수, 3:목, 4:금, 5:토, 6:일 try: print("\n[증시자금동향 (신용잔고, 펀드자금 잔고)]") metaCrawler.crawl_money_trend(stockFileName) - slackBot.sendMsg("2. done meta data...") + bot.sendMsg("2. done meta data...") break except: ERROR_COUNT += 1 @@ -78,7 +78,7 @@ if week in (0, 1, 2, 3, 4): # 0:월, 1:화, 2:수, 3:목, 4:금, 5:토, 6:일 try: print("\n[국내 시장금리]") metaCrawler.crawl_interest_rates(stockFileName) - slackBot.sendMsg("3. done interest rates...") + bot.sendMsg("3. done interest rates...") break except: ERROR_COUNT += 1 @@ -93,7 +93,7 @@ if week in (0, 1, 2, 3, 4): # 0:월, 1:화, 2:수, 3:목, 4:금, 5:토, 6:일 try: print("\n[투자자별 매매동향(Trading_Trend)]") metaCrawler.crawl_trading_trend(stockFileName) - slackBot.sendMsg("4. done trade trend...") + bot.sendMsg("4. done trade trend...") break except: ERROR_COUNT += 1 @@ -108,7 +108,7 @@ if week in (0, 1, 2, 3, 4): # 0:월, 1:화, 2:수, 3:목, 4:금, 5:토, 6:일 try: print("\n[환율 (USD, JPY, EUR, CNY, HKD, GBP, CAD, CHF, AUD, THB, INR, PHP, BRL, VND, RUB, TWD')]") metaCrawler.crawl_exchange(stockFileName) - slackBot.sendMsg("5. done exchange data...") + bot.sendMsg("5. done exchange data...") break except: ERROR_COUNT += 1 @@ -123,7 +123,7 @@ if week in (0, 1, 2, 3, 4): # 0:월, 1:화, 2:수, 3:목, 4:금, 5:토, 6:일 try: print("\n[원유 (WTI), 국제금, COPPER, NATURALGAS, CORN, SOYBEAN 등]") metaCrawler.crawl_meterials(stockFileName) - slackBot.sendMsg("6. done additional data...") + bot.sendMsg("6. done additional data...") break except: ERROR_COUNT += 1 @@ -140,19 +140,19 @@ if week in (0, 1, 2, 3, 4): # 0:월, 1:화, 2:수, 3:목, 4:금, 5:토, 6:일 print("\n[국내 ETF 수집]") stockCrawler.crawl_etf_stocks(stockFileName) - slackBot.sendMsg("7. done etf stocks...") + bot.sendMsg("7. done etf stocks...") print("\n[국내 종목 수집]") stockCrawler.crawl_stocks(stockFileName) - slackBot.sendMsg("8. done stocks...") + bot.sendMsg("8. done stocks...") print("\n[US 종목 수집]") stockCrawler.crawl_special_stocks(stockFileName) - slackBot.sendMsg("9. done US stocks...") + bot.sendMsg("9. done US stocks...") @@ -164,7 +164,7 @@ if week in (0, 1, 2, 3, 4): # 0:월, 1:화, 2:수, 3:목, 4:금, 5:토, 6:일 analyzerSqlite.analyzeDaily() analyzerSqlite.analyzeGrouping("weekly") analyzerSqlite.analyzeGrouping("monthly") - slackBot.sendMsg("10. analyze...") + bot.sendMsg("10. analyze...") @@ -186,11 +186,7 @@ if week in (0, 1, 2, 3, 4): # 0:월, 1:화, 2:수, 3:목, 4:금, 5:토, 6:일 os.mkdir(outPath) analyzerSqlite.findCandidates(outPath) - slackBot.sendMsg("11. done decision...") - - - - + bot.sendMsg("11. done decision...") print("time : %6.2f 초", (time.time() - start)) diff --git a/hts/HTS.py b/hts/HTS.py index f5365e9..458ff71 100644 --- a/hts/HTS.py +++ b/hts/HTS.py @@ -8,7 +8,7 @@ import time import sqlite3 from datetime import datetime, timedelta from hts.OrderItem import OrderItem -from stock.util.SlackBot import SlackBot +from stock.util.TelegramBot import TelegramBot class HTS: @@ -21,7 +21,7 @@ class HTS: def __init__(self, RESOURCE_PATH): self.RESOURCE_PATH = RESOURCE_PATH - self.slackBot = SlackBot() + self.bot = TelegramBot() self.connect2DB(os.path.join( RESOURCE_PATH, "hts.db")) return @@ -164,14 +164,14 @@ class HTS: objCpCybos = win32com.client.Dispatch("CpUtil.CpCybos") bConnect = objCpCybos.IsConnect if (bConnect == 0): - self.slackBot.sendMsg("PLUS가 정상적으로 연결되지 않음. ") + self.bot.sendMsg("PLUS가 정상적으로 연결되지 않음. ") print("PLUS가 정상적으로 연결되지 않음. ") exit() objTrade = win32com.client.Dispatch("CpTrade.CpTdUtil") initCheck = objTrade.TradeInit(0) if (initCheck != 0): - self.slackBot.sendMsg("주문 초기화 실패") + self.bot.sendMsg("주문 초기화 실패") print("주문 초기화 실패") exit() @@ -203,16 +203,16 @@ class HTS: rqRet = objStockOrder.GetDibMsg1() print("통신상태", rqStatus, rqRet) if rqStatus != 0: - self.slackBot.sendMsg("통신상태: "+ str(rqStatus)+" ("+str(rqRet)+")") + self.bot.sendMsg("통신상태: "+ str(rqStatus)+" ("+str(rqRet)+")") return None orderNum = objStockOrder.GetHeaderValue(0) if (type == "1"): - self.slackBot.post_to_slack(stock_code, stock_code, "SELL", price, count) + self.bot.post(stock_code, stock_code, "SELL", price, count) print ("(SELL", count, price, ")") else: - self.slackBot.post_to_slack(stock_code, stock_code, "BUY", price, count) + self.bot.post_to_slack(stock_code, stock_code, "BUY", price, count) print ("(BUY", count, price, ")") return orderNum diff --git a/stock/util/SlackBot.py b/stock/util/SlackBot.py index 58f06f7..a9122b4 100644 --- a/stock/util/SlackBot.py +++ b/stock/util/SlackBot.py @@ -1,70 +1,80 @@ from slack_sdk import WebClient from slack_sdk.errors import SlackApiError from datetime import datetime - +from slack_cleaner2 import * class SlackBot: + enable = None BOT_TOKEN = None CHANNEL_ID = None client = None - def __init__(self): + def __init__(self, enable=True): # family # self.BOT_TOKEN = "xoxb-1214605084611-4694289701799-1lCW10baLrihe60DvW1oZ32V" # self.CHANNEL_ID = "C021KN0GG94" # ncue - self.BOT_TOKEN = "xoxb-305350122625-5129491733572-JsBui5wmj7bBoSibRvtz1trj" - self.CHANNEL_ID = "C03TNCAHQHE" + #self.BOT_TOKEN = "xoxb-305350122625-5129491733572-JsBui5wmj7bBoSibRvtz1trj" + #self.CHANNEL_ID = "C062UAHQWLC" + #self.client = WebClient(token=self.BOT_TOKEN) + + # ncue + self.BOT_TOKEN = "xoxp-305350122625-305798290339-6093851456290-295074ffaa9688dbe97d008bc53bbe11" + self.CHANNEL_ID = "C062UAHQWLC" self.client = WebClient(token=self.BOT_TOKEN) + self.enable = enable return - def post_live_to_slack(self, stock_code, stock_name, close, macd): - try: - this_time = datetime.now() - text = "ALIVE ({}, {}, {}, close: {}, macd: {:.2f}".format(this_time.strftime('%Y-%m-%d %H:%M:%S'), stock_code, stock_name, close, macd) - result = self.client.chat_postMessage( - channel=self.CHANNEL_ID, - text=text - ) + def alarm_live(self, stock_code, stock_name): + if self.enable: + try: + this_time = datetime.now() + text = "ALIVE (" + this_time.strftime('%Y-%m-%d %H:%M:%S') + ") " + stock_code + "(" + stock_name +")" + result = self.client.chat_postMessage( + channel=self.CHANNEL_ID, + text=text + ) + print(text) - except SlackApiError as e: - print(f"Error posting message: {e}") + except SlackApiError as e: + print(f"Error posting message: {e}") return - def post_to_slack(self, stock_code, stock_name, type, price, count): - try: - this_time = datetime.now() - text = "DATE TIME:" + this_time.strftime('%Y-%m-%d %H:%M:%S') + ", " + "stock_code:" + stock_code + ", " + "stock_name:" + stock_name + ", " + "type:" + type + ", " + "price:" + str(price) + ", " + "count:" + str(count) - result = self.client.chat_postMessage( - channel=self.CHANNEL_ID, - text=text - ) - print(text) + def post(self, stock_code, stock_name, type, price, count): + if self.enable: + try: + this_time = datetime.now() + text = "DATE TIME:" + this_time.strftime('%Y-%m-%d %H:%M:%S') + ", " + "stock_code:" + stock_code + ", " + "stock_name:" + stock_name + ", " + "type:" + type + ", " + "price:" + str(price) + ", " + "count:" + str(count) + result = self.client.chat_postMessage( + channel=self.CHANNEL_ID, + text=text + ) + print(text) - except SlackApiError as e: - print(f"Error posting message: {e}") + except SlackApiError as e: + print(f"Error posting message: {e}") return def sendMsg(self, msg): - try: - this_time = datetime.now() - text = "DATE TIME:" + this_time.strftime('%Y-%m-%d %H:%M:%S') + ", " + "msg:" + msg - result = self.client.chat_postMessage( - channel=self.CHANNEL_ID, - text=text - ) - print(text) + if self.enable: + try: + this_time = datetime.now() + text = "DATE TIME:" + this_time.strftime('%Y-%m-%d %H:%M:%S') + ", " + "msg:" + msg + result = self.client.chat_postMessage( + channel=self.CHANNEL_ID, + text=text + ) + print(text) - except SlackApiError as e: - print(f"Error posting message: {e}") + except SlackApiError as e: + print(f"Error posting message: {e}") return - if __name__ == "__main__": this_time = datetime.now() stock_code = "252670" @@ -73,5 +83,7 @@ if __name__ == "__main__": price = 2000 count = 2 - slackBot = SlackBot() - slackBot.post_to_slack(stock_code, stock_name, type, price, count) + slackBot = SlackBot(False) + slackBot.post(stock_code, stock_name, type, price, count) + + diff --git a/stock/util/TelegramBot.py b/stock/util/TelegramBot.py new file mode 100644 index 0000000..12108c3 --- /dev/null +++ b/stock/util/TelegramBot.py @@ -0,0 +1,77 @@ +from datetime import datetime +import telegram +import asyncio + +class TelegramBot: + enable = None + BOT_TOKEN = None + CHANNEL_ID = None + client = None + + def __init__(self, enable=True): + """ + botname: coinbot + username for the bot: ncue_coin_bot + token to access the HTTP API: 6435061393:AAHOh9wB5yGNGUdb3SfCYJrrWTBe7wgConM + + botname: lottobot + username for the bot: ncue_lotto_bot + token to access the HTTP API:6791293398:AAFi1zrQTs6UmuHycAuNdsBgHDHaHcOJcYA + + botname: stockbot + username for the bot: ncue_stock_bot + token to access the HTTP API: 6874078562:AAEHxGDavfc0ssAXPQIaW8JGYmTR7LNUJOw + """ + self.botname = "coinbot" + self.username = "ncue_coin_bot" + self.token = "6435061393:AAHOh9wB5yGNGUdb3SfCYJrrWTBe7wgConM" + self.chat_id = '574661323' + self.client = telegram.Bot(token=self.token) + + self.enable = enable + return + + def alarm_live(self, stock_code, stock_name): + if self.enable: + this_time = datetime.now() + text = "ALIVE (" + this_time.strftime('%Y-%m-%d %H:%M:%S') + ") " + stock_code + "(" + stock_name +")" + asyncio.run( + self.client.sendMessage(chat_id=self.chat_id, text=text) + ) + print(text) + + return + + def post(self, stock_code, stock_name, type, price, count): + if self.enable: + this_time = datetime.now() + text = "DATE TIME:" + this_time.strftime('%Y-%m-%d %H:%M:%S') + ", " + "stock_code:" + stock_code + ", " + "stock_name:" + stock_name + ", " + "type:" + type + ", " + "price:" + str(price) + ", " + "count:" + str(count) + asyncio.run( + self.client.sendMessage(chat_id=self.chat_id, text=text) + ) + print(text) + return + + def sendMsg(self, msg): + if self.enable: + this_time = datetime.now() + text = "DATE TIME:" + this_time.strftime('%Y-%m-%d %H:%M:%S') + ", " + "msg:" + msg + asyncio.run( + self.client.sendMessage(chat_id=self.chat_id, text=text) + ) + print(text) + + return + +if __name__ == "__main__": + this_time = datetime.now() + stock_code = "252670" + stock_name = "x2" + type = "BUY" + price = 2000 + count = 2 + + telegramBot = TelegramBot(True) + telegramBot.post(stock_code, stock_name, type, price, count) + +