import os import time from datetime import datetime import json import requests import traceback import random from colorama import Fore, Back, Style, init import http.server import socketserver def http_saba(): # ポート番号とホストの定義 PORT = 7860 HOST = "0.0.0.0" # ハンドラーの設定(現在のディレクトリのファイルを公開) Handler = http.server.SimpleHTTPRequestHandler # サーバーの起動 with socketserver.TCPServer((HOST, PORT), Handler) as httpd: print(f"Serving at http://{HOST}:{PORT}") print("Server起動。") # サーバーを永久に実行 httpd.serve_forever() def log(msg, type): init() time_datetime = datetime.now() if type == 1: # 通常ログ(白 or 緑) print(f"{time_datetime}{Fore.GREEN}[log]: {msg}") elif type == 2: # 警告(黄色) print(f"{time_datetime}{Fore.YELLOW}[warn]: {msg}") elif type == 3: # エラー(赤) print(f"{time_datetime}{Fore.RED}[error]: {msg}") print(Fore.RED) traceback.print_exc() def System_up(sec): START_TIME = sec while START_TIME > 0: log(f"起動まで、{START_TIME}秒",1) START_TIME = START_TIME - 1 time.sleep(1) System_up(3) log("起動しました。",1) # ===== Channel.io 設定 ===== CHANNEL_ID = os.getenv("CHIO_CH_ID")#"200605" チャンネル if not CHANNEL_ID: raise RuntimeError("環境変数 CHIO_CH_ID が設定されていません") GROUP_ID = os.getenv("CHIO_GR_ID")#"534868" グループ if not GROUP_ID: raise RuntimeError("環境変数 CHIO_GR_ID が設定されていません") MESSAGES_URL = f"https://desk-api.channel.io/desk/channels/{CHANNEL_ID}/groups/{GROUP_ID}/messages" X_ACCOUNT = os.getenv("CHIO_TOKEN") #トークン if not X_ACCOUNT: raise RuntimeError("環境変数 CHIO_TOKEN が設定されていません") HEADERS = { "accept": "application/json", "accept-language": "ja", "content-type": "application/json", "x-account": X_ACCOUNT, } PARAMS = { "sortOrder": "desc", "limit": 50, } # ===== Utils ===== def ramdom_msg(): date = [ {"no":0,"by":"name","text":"message","call":"addres"},#0 {"no":1,"by":"name_00","text":"message","call":"addres"},#0 {"no":2,"by":"name_01","text":"message_02","call":"addres"},#0 {"no":3,"by":"name_02","text":"message_03","call":"addres"},#0 ] rand = random.randint(0, 3)#ランダム最大値指定。 if rand == 0: ramdom_msg()#再起 log("辞書の0が指定されたから無視",1) elif rand == 1: try: text = date[1]["text"] by = date[1]["by"] call = date[1]["call"] send_to_channel(f"広告:{text}\n{by}様より。call:{call}") except Exception as e: log(f"広告{rand}番エラー:{e}",3) elif rand == 2: try: text = date[2]["text"] by = date[2]["by"] call = date[2]["call"] send_to_channel(f"広告:{text}\n{by}様より。call:{call}") except Exception as e: log(f"広告{rand}番エラー:{e}",3) elif rand == 3: try: text = date[3]["text"] by = date[3]["by"] call = date[3]["call"] send_to_channel(f"広告:{text}\n{by}様より。call:{call}") except Exception as e: log(f"広告{rand}番エラー:{e}",3) elif rand == 4: try: text = date[4]["text"] by = date[4]["by"] call = date[4]["call"] send_to_channel(f"広告:{text}\n{by}様より。call:{call}") except Exception as e: log(f"広告{rand}番エラー:{e}",4) def get_messages(): try: res = requests.get( MESSAGES_URL, headers=HEADERS, params=PARAMS, timeout=30, ) res.raise_for_status() return res.json().get("messages", []) except Exception as e: log(f"MSG取得関数に失敗:{e}",3) def send_to_channel(text): try: payload = { "requestId": f"desk-web-{int(time.time() * 1000)}", "blocks": [ { "type": "text", "value": text } ], } res = requests.post( MESSAGES_URL, headers=HEADERS, data=json.dumps(payload), timeout=30, ) res.raise_for_status() except Exception as e: log(f"MSG送信関数に失敗:{e}",1) #def send_to_channel_file(file_url): # try: # #get_request送る->https://files.electrohaxz.host/にupする->リンクをfile_urlに入れて送る。 # payload = { # "requestId": f"desk-web-{int(time.time() * 1000)}", # "blocks": [ # { # "type": "text", # "value": file_url # } # ], # } # # res = requests.post( # MESSAGES_URL, # headers=HEADERS, # data=json.dumps(payload), # timeout=30, # ) # res.raise_for_status() # # except Exception as e: # log(f"ファイルアップロード関数に失敗:{e}",1) # ===== Main Loop ===== log("BOTのメインループを開始します。",1) def main(): while True: try: NEXT_SEND = 120 while NEXT_SEND > 0: #log(f"次回まであと、{NEXT_SEND}秒",1) NEXT_SEND = NEXT_SEND - 1 time.sleep(1) time_datetime= datetime.now() send_to_channel(f"浮上。つまり、私がキタ━━━━(゚∀゚)━━━━!!。\n 現在時刻は多分+UTCで{time_datetime}です!") ramdom_msg() send_to_channel(f"\(^^)/眠くなったからおやすみ。また時報&宣伝します。\(^^)/") log(f"送信しました。",1) except Exception as e: log(f"メインループ:{e}",3) http_saba() if __name__ == "__main__": main()