Compare commits
10 Commits
master
...
2024-05-01
Author | SHA1 | Date | |
---|---|---|---|
6a38635a1d | |||
99e8c84ea6 | |||
cbcf468009 | |||
682e2a404a | |||
5c29c98550 | |||
aa24383f54 | |||
ebb36ac844 | |||
6849a5c801 | |||
d8a9efffbe | |||
bcca39152c |
1
.gitignore
vendored
1
.gitignore
vendored
@ -6,3 +6,4 @@ msgid
|
||||
tmppic.jpg
|
||||
venv
|
||||
__pycache__/
|
||||
twitch-tgbot.cfg
|
||||
|
@ -1,6 +0,0 @@
|
||||
streamer = "1n7er"
|
||||
appid="addid"
|
||||
appsecret="addsecret"
|
||||
tgtoken = "token"
|
||||
tgchat = "chat"
|
||||
period = 300
|
@ -1,3 +1,2 @@
|
||||
twitchAPI==2.5.7.1
|
||||
termcolor
|
||||
pyTelegramBotAPI==4.8.0
|
||||
telebot
|
47
src/log_msg.py
Normal file
47
src/log_msg.py
Normal file
@ -0,0 +1,47 @@
|
||||
import logging
|
||||
from logging.handlers import TimedRotatingFileHandler
|
||||
import sys
|
||||
log_format = logging.Formatter('%(asctime)s %(levelname)s:%(message)s')
|
||||
log_file = 'output.log'
|
||||
|
||||
|
||||
class CustomFormatter(logging.Formatter):
|
||||
|
||||
grey = "\x1b[38;20m"
|
||||
yellow = "\x1b[33;20m"
|
||||
red = "\x1b[31;20m"
|
||||
bold_red = "\x1b[31;1m"
|
||||
reset = "\x1b[0m"
|
||||
format = "%(asctime)s %(levelname)s - %(message)s"
|
||||
|
||||
FORMATS = {
|
||||
logging.DEBUG: grey + format + reset,
|
||||
logging.INFO: grey + format + reset,
|
||||
logging.WARNING: yellow + format + reset,
|
||||
logging.ERROR: red + format + reset,
|
||||
logging.CRITICAL: bold_red + format + reset
|
||||
}
|
||||
|
||||
def format(self, record):
|
||||
log_fmt = self.FORMATS.get(record.levelno)
|
||||
formatter = logging.Formatter(log_fmt)
|
||||
return formatter.format(record)
|
||||
|
||||
|
||||
class MyLog:
|
||||
|
||||
def __init__(self):
|
||||
self.logger = logging.getLogger("main")
|
||||
self.logger.setLevel(logging.DEBUG)
|
||||
# Console logging
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setFormatter(log_format)
|
||||
|
||||
console = console_handler
|
||||
console.setFormatter(CustomFormatter())
|
||||
self.logger.addHandler(console)
|
||||
|
||||
file_handler = TimedRotatingFileHandler(log_file, when='midnight')
|
||||
file_handler.setFormatter(log_format)
|
||||
self.logger.addHandler(file_handler)
|
||||
self.logger.propagate = False
|
38
src/parse_config.py
Normal file
38
src/parse_config.py
Normal file
@ -0,0 +1,38 @@
|
||||
from dataclasses import dataclass, asdict
|
||||
import configparser
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
class Config:
|
||||
streamer: str
|
||||
app_id: str
|
||||
app_secret: str
|
||||
target_tg_chat: str
|
||||
tg_token: str
|
||||
check_period: int
|
||||
cleanup_msg: bool
|
||||
|
||||
@classmethod
|
||||
def load(cls, config_path: str = "twitch-tgbot.cfg") -> 'Config':
|
||||
"""
|
||||
Эта функция либо читает существующий конфиг, либо создает новый.
|
||||
Возвращает объект конфига (configparser.ConfigParser())
|
||||
"""
|
||||
config_file = configparser.ConfigParser()
|
||||
# Читаем конфиг, если пустой - заполняем
|
||||
if not config_file.read(config_path) or not config_file.has_section('twitch'):
|
||||
config_file.add_section('twitch')
|
||||
twitch = config_file['twitch']
|
||||
config = Config(
|
||||
streamer=twitch.get('streamer',fallback='the_viox'),
|
||||
app_id=twitch.get('app_id',fallback=''),
|
||||
app_secret=twitch.get('app_secret',fallback=''),
|
||||
target_tg_chat=twitch.get('target_tg_chat',fallback=''),
|
||||
tg_token=twitch.get('tg_token',fallback=''),
|
||||
check_period=twitch.getint('check_period',fallback=10),
|
||||
cleanup_msg=twitch.getboolean('cleanup_msg',fallback=True)
|
||||
)
|
||||
with open(config_path, 'w') as cfg_file:
|
||||
config_file.read_dict({'twitch': asdict(config)})
|
||||
config_file.write(cfg_file)
|
||||
return config
|
@ -1,15 +1,8 @@
|
||||
#!/usr/bin/python3
|
||||
#!/usr/bin/env python3
|
||||
import time
|
||||
import os
|
||||
import sys
|
||||
import logging
|
||||
|
||||
sys.path.append(os.path.abspath(os.path.curdir))
|
||||
import config_python
|
||||
|
||||
from twitchAPI.twitch import Twitch
|
||||
from logging.handlers import TimedRotatingFileHandler
|
||||
from termcolor import colored
|
||||
import telebot
|
||||
from telebot.types import InputFile
|
||||
from telebot import types
|
||||
@ -17,12 +10,8 @@ from datetime import datetime
|
||||
import requests
|
||||
import shutil
|
||||
|
||||
streamer = config_python.streamer
|
||||
app_id = config_python.appid
|
||||
app_secret = config_python.appsecret
|
||||
|
||||
log_format = logging.Formatter('%(asctime)s %(levelname)s:%(message)s')
|
||||
log_file = 'output.log'
|
||||
from parse_config import Config
|
||||
from log_msg import MyLog
|
||||
|
||||
|
||||
def stream_message_worker(data: dict):
|
||||
@ -55,7 +44,7 @@ def stream_message_worker(data: dict):
|
||||
"Длительность: " + str(stream_duration)
|
||||
|
||||
# Готовим кнопку
|
||||
stream_button = types.InlineKeyboardButton('Открыть стрим', url='https://twitch.tv/'+streamer)
|
||||
stream_button = types.InlineKeyboardButton('Открыть стрим', url='https://twitch.tv/'+config_python.streamer)
|
||||
keyboard = types.InlineKeyboardMarkup()
|
||||
keyboard.add(stream_button)
|
||||
|
||||
@ -71,7 +60,7 @@ def stream_message_worker(data: dict):
|
||||
|
||||
if msgid == 0:
|
||||
# Отправляем новое сообщение
|
||||
send_message = bot.send_photo(config_python.tgchat, InputFile('tmppic.jpg'), message, reply_markup=keyboard,
|
||||
send_message = bot.send_photo(config_python.target_tg_chat, InputFile('tmppic.jpg'), message, reply_markup=keyboard,
|
||||
parse_mode='MarkdownV2')
|
||||
print(send_message)
|
||||
msgid = send_message.message_id
|
||||
@ -82,9 +71,9 @@ def stream_message_worker(data: dict):
|
||||
# Готовим медиа для отправки
|
||||
media = telebot.types.InputMediaPhoto(InputFile('tmppic.jpg'))
|
||||
# Редактируем фотку
|
||||
edit_msg_media = bot.edit_message_media(media, config_python.tgchat, msgid, reply_markup=keyboard)
|
||||
edit_msg_media = bot.edit_message_media(media, config_python.target_tg_chat, msgid, reply_markup=keyboard)
|
||||
# Редактируем текст
|
||||
edit_msg_caption = bot.edit_message_caption(message, config_python.tgchat, msgid, reply_markup=keyboard,
|
||||
edit_msg_caption = bot.edit_message_caption(message, config_python.target_tg_chat, msgid, reply_markup=keyboard,
|
||||
parse_mode='MarkdownV2')
|
||||
except telebot.apihelper.ApiTelegramException as e:
|
||||
log.error(e)
|
||||
@ -92,7 +81,7 @@ def stream_message_worker(data: dict):
|
||||
|
||||
# Если стрим не идет
|
||||
def no_stream_msg_worker():
|
||||
log.info(streamer + " Не стримит")
|
||||
log.info(config_python.streamer + " Не стримит")
|
||||
# Проверяем наличие файла
|
||||
if os.path.exists('msgid'):
|
||||
# Если файл существует - читаем
|
||||
@ -102,11 +91,11 @@ def no_stream_msg_worker():
|
||||
# Если пустой - удаляем
|
||||
os.remove('msgid')
|
||||
else:
|
||||
if config_python.delete_msg:
|
||||
if config_python.cleanup_msg:
|
||||
# Если не пустой, то удаляем сообщение по айдишнику
|
||||
try:
|
||||
# Удаляем сообщение
|
||||
edit_msg = bot.delete_message(config_python.tgchat, int(msgid))
|
||||
edit_msg = bot.delete_message(config_python.target_tg_chat, int(msgid))
|
||||
except telebot.apihelper.ApiTelegramException as e:
|
||||
log.error(e)
|
||||
# В конце удаляем айди сообщения
|
||||
@ -121,14 +110,9 @@ def check_alive():
|
||||
"""
|
||||
|
||||
# Получаем инфо о стримере, если не получается, выходим с ошибкой
|
||||
resolved_id = twitch_client.get_users(logins=[streamer])
|
||||
resolved_id = twitch_client.get_users(logins=[config_python.streamer])
|
||||
if not resolved_id['data']:
|
||||
log.error(
|
||||
colored(
|
||||
"Аккаунт " + streamer + " не найден",
|
||||
'red',
|
||||
)
|
||||
)
|
||||
log.error("Аккаунт " + config_python.streamer + " не найден")
|
||||
# Достаем ID стримера из инфо
|
||||
user_id = resolved_id['data'][0]['id']
|
||||
# Получаем стримы
|
||||
@ -141,33 +125,13 @@ def check_alive():
|
||||
no_stream_msg_worker()
|
||||
|
||||
|
||||
def get_console_handler():
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setFormatter(log_format)
|
||||
return console_handler
|
||||
|
||||
|
||||
def get_file_handler():
|
||||
file_handler = TimedRotatingFileHandler(log_file, when='midnight')
|
||||
file_handler.setFormatter(log_format)
|
||||
return file_handler
|
||||
|
||||
|
||||
def get_logger(logger_name):
|
||||
logger = logging.getLogger(logger_name)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
logger.addHandler(get_console_handler())
|
||||
logger.addHandler(get_file_handler())
|
||||
logger.propagate = False
|
||||
return logger
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
log = get_logger("main")
|
||||
log = MyLog().logger
|
||||
log.info("Запущен")
|
||||
twitch_client = Twitch(app_id, app_secret)
|
||||
bot = telebot.TeleBot(config_python.tgtoken)
|
||||
config_python = Config.load()
|
||||
twitch_client = Twitch(config_python.app_id, config_python.app_secret)
|
||||
bot = telebot.TeleBot(config_python.tg_token)
|
||||
|
||||
while True:
|
||||
check_alive()
|
||||
time.sleep(config_python.period)
|
||||
time.sleep(config_python.check_period)
|
Loading…
Reference in New Issue
Block a user