├── utils
├── __version__.py
├── common.py
└── db_model.py
├── .gitignore
├── docker-compose.yml
├── Pipfile
├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
├── FUNDING.yml
└── workflows
│ └── main.yml
├── config.py
├── Dockerfile
├── logger.py
├── config.yml.example
├── README.md
├── Pipfile.lock
├── LICENSE
└── main.py
/utils/__version__.py:
--------------------------------------------------------------------------------
1 | __version__ = "dev"
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .*
2 | *.pyc
3 | config.yml
4 | !.gitignore
5 | logs/*
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: "3.9"
2 | services:
3 | keyword_alert_bot:
4 | # build: .
5 | image: yha8897/keyword_alert_bot:latest
6 | volumes:
7 | - ./config.yml:/app/config.yml
8 | - ./db/:/app/db/
9 |
10 | # ports:
11 | # - "8080:8080"
12 |
--------------------------------------------------------------------------------
/Pipfile:
--------------------------------------------------------------------------------
1 | [[source]]
2 | name = "pypi"
3 | url = "https://pypi.org/simple"
4 | verify_ssl = true
5 |
6 | [dev-packages]
7 |
8 | [packages]
9 | telethon = "*"
10 | pysocks = "*"
11 | peewee = "*"
12 | pyyaml = "*"
13 | diskcache = "*"
14 | asyncstdlib = "*"
15 | colorama = "*"
16 | text-box-wrapper = "*"
17 |
18 | [requires]
19 | python_version = "3.11"
20 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug反馈模版 Bug report
3 | about: 提交Bug有助于改进程序。Create a report to help us improve
4 | title: "[BUG]"
5 | labels: bug
6 | assignees: Hootrix
7 |
8 | ---
9 |
10 | **问题描述 Describe the bug**
11 | 请简洁明了地描述您遇到的问题。A clear and concise description of what the bug is.
12 |
13 | **订阅信息 command Info**
14 | 请提供相关命令和信息,例如:
15 | /subscribe 优惠券,Booked https://t.me/tianfutong
16 |
17 |
--------------------------------------------------------------------------------
/config.py:
--------------------------------------------------------------------------------
1 | import os,yaml,sys
2 |
3 | __all__ = [
4 | 'config',
5 | '_current_path'
6 | ]
7 | _current_path = os.path.dirname(os.path.realpath(__file__))
8 | config_file = f'{_current_path}/config.yml'
9 |
10 | if not os.path.exists(config_file):
11 | print(f"Config file '{config_file}' not found. Please configure using 'config.yml.default'.")
12 | sys.exit(1)
13 |
14 | with open(config_file) as _f:
15 | config = yaml.load(_f.read(),Loader = yaml.SafeLoader)
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: 功能需求模版 Feature request
3 | about: 提出一个新功能建议,以帮助我们改进项目。Suggest an idea for this project
4 | title: '[FEATURE]'
5 | labels: enhancement
6 | assignees: Hootrix
7 |
8 | ---
9 |
10 | **功能需求是否与您遇到的问题有关?请描述。Is your feature request related to a problem? Please describe.**
11 | 请简洁明了地描述您遇到的问题。A clear and concise description of what the problem is.
12 |
13 | **描述您想要的解决方案 Describe the solution you'd like**
14 | 请简洁明了地描述您希望实现的功能。A clear and concise description of what you want to happen.
15 |
16 | ---
17 |
18 | 谢谢您的建议!开发者在有空闲时间时会审查您的建议,并安排相应计划。欢迎一起完善这个项目。
19 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.11-slim AS dependency-builder
2 | WORKDIR /app
3 | COPY . /app
4 | RUN pip install pipenv && \
5 | pipenv requirements > requirements.txt && \
6 | pip install --timeout=60 --retries=5 --target=/site-packages -r requirements.txt
7 |
8 | ADD https://github.com/krallin/tini/releases/download/v0.19.0/tini-static /tini
9 | RUN chmod +x /tini
10 |
11 | FROM gcr.io/distroless/python3-debian12:nonroot
12 | WORKDIR /app
13 | COPY --from=dependency-builder /site-packages /site-packages
14 | COPY --from=dependency-builder /app/ /app/
15 | COPY --from=dependency-builder /tini /tini
16 | ENV PYTHONPATH=/site-packages
17 | USER nonroot
18 | ENTRYPOINT ["/tini", "--"]
19 | CMD ["/usr/bin/python", "main.py"]
20 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: [Hootrix] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
14 |
--------------------------------------------------------------------------------
/logger.py:
--------------------------------------------------------------------------------
1 | import logging,os
2 | from logging.handlers import RotatingFileHandler
3 | from config import _current_path,config
4 |
5 | __all__ = [
6 | 'logger'
7 | ]
8 |
9 | __LOG_DIR = f'{_current_path}/logs/'
10 | __LOG_NAME = 'keyword_alert.log'
11 | if config['logger']['path']:
12 | __LOG_DIR = config['logger']['path'].rstrip('/')
13 |
14 | not os.path.exists(__LOG_DIR) and os.makedirs(__LOG_DIR)
15 | __LOG_FILE = f"{__LOG_DIR}/{__LOG_NAME}"
16 | __level = getattr(logging,config['logger']['level']) if hasattr(logging,config['logger']['level']) else 'ERROR'
17 | handler = RotatingFileHandler(__LOG_FILE, maxBytes=5*1024*1024, backupCount=10) # 最大50MB日志
18 | formatter = logging.Formatter(fmt='[%(levelname)s][%(name)s][%(asctime)s]-->%(message)s',datefmt='%Y-%m-%d %H:%M:%S%Z')
19 | handler.setFormatter(formatter)
20 |
21 | logger = logging.getLogger('keyword_alert.root')
22 | logger.setLevel(__level)
23 | logger.addHandler(handler)
--------------------------------------------------------------------------------
/config.yml.example:
--------------------------------------------------------------------------------
1 | #账户配置描述信息
2 |
3 | # Config BOT and account
4 | account:
5 | # 监听频道信息的账户
6 | api_id : '1400003'
7 | api_hash : 'd11xxxxx112a7e059e831'
8 | phone : '+86190000010'
9 | username : 'cliasaxxxev'
10 |
11 | # 发送消息的bot token
12 | bot_token : '1000007:AAHNh8axxxxxxxxxxxxxxxxHA'
13 | bot_username : 'keyxxxxxrt_bot' # 同参数 bot_name
14 |
15 | # LOG
16 | logger:
17 | path: null # e.g. /root/absolute-path/ default null: {_current_path}/logs/
18 | level: INFO # FATAL,ERROR,WARN,INFO,DEBUG,NOTSET
19 |
20 | # 代理
21 | proxy:
22 | type: SOCKS5 # e.g. SOCKS4, SOCKS5, HTTP
23 | address: null # e.g. 127.0.0.1
24 | port: null # e.g. 1088
25 |
26 |
27 | # 自动退群/频道(针对无有效订阅记录的群/频道)
28 | auto_leave_channel: false
29 |
30 |
31 | # 消息去重规则
32 | # SUBSCRIBE_ID: 默认规则 按照订阅去重
33 | # MESSAGE_ID: 按消息id去重(若该消息同时命中多条订阅,只返回第一条订阅提醒)
34 | msg_unique_rule: SUBSCRIBE_ID # default SUBSCRIBE_ID
35 |
36 | # 非公共服务
37 | # 此bot只为指定的用户服务
38 | private_service: false
39 | authorized_users:
40 | - 123456789
41 | - 987654321
42 |
43 | # 禁止监听机器人发送的消息(仅限群组)
44 | # 比如,有些群里有自动回复机器人,回复的都是重复的消息;或者一些广告机器人加群之后开始刷屏
45 | block_bot_msg: false # default allow
46 |
--------------------------------------------------------------------------------
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | name: CI/CD Pipeline
2 |
3 | on:
4 | push:
5 | branches:
6 | # - dev.20230419 # debug
7 | - master
8 |
9 | jobs:
10 | build-and-push:
11 | runs-on: ubuntu-latest
12 |
13 | steps:
14 | - name: Check out code
15 | uses: actions/checkout@v2
16 | with:
17 | fetch-depth: 2
18 |
19 | - name: Set up QEMU
20 | uses: docker/setup-qemu-action@v2
21 |
22 | - name: Set up Docker Buildx
23 | uses: docker/setup-buildx-action@v2
24 |
25 | - name: Set up Python 3.11
26 | uses: actions/setup-python@v3
27 | with:
28 | python-version: 3.11
29 |
30 | - name: Install pipenv
31 | run: |
32 | python -m pip install --upgrade pip
33 | python -m pip install pipenv
34 |
35 | - name: Check for file changes
36 | id: file_check
37 | run: |
38 | if git diff --name-only HEAD^ | grep -q ".py$"; then
39 | echo "::set-output name=updated::true"
40 | else
41 | echo "::set-output name=updated::false"
42 | fi
43 |
44 | - name: Install dependencies and lock
45 | if: steps.file_check.outputs.updated == 'true'
46 | run: |
47 | pipenv install --dev
48 | pipenv lock
49 |
50 | - name: Create version file
51 | run: |
52 | COMMIT_ID=$(git rev-parse --short HEAD)
53 | echo "__version__ = '$(TZ='Asia/Shanghai' date +'%Y%m%d').$COMMIT_ID'" > utils/__version__.py
54 |
55 |
56 | - name: Login to DockerHub
57 | uses: docker/login-action@v1
58 | with:
59 | username: ${{ secrets.DOCKER_HUB_USERNAME }}
60 | password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}
61 |
62 | - name: Build and push Docker image
63 | if: steps.file_check.outputs.updated == 'true'
64 | uses: docker/build-push-action@v2
65 | with:
66 | context: .
67 | platforms: linux/amd64,linux/arm64
68 | push: true
69 | tags: yha8897/keyword_alert_bot:latest
70 |
71 | - name: Create release
72 | if: steps.file_check.outputs.updated == 'true'
73 | env:
74 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
75 | run: |
76 | VERSION=$(python -c "from utils.__version__ import __version__; print(__version__)")
77 | echo $VERSION
78 | gh release create $VERSION
79 |
--------------------------------------------------------------------------------
/utils/common.py:
--------------------------------------------------------------------------------
1 | from config import config
2 | from colorama import Fore, Style, init
3 | from text_box_wrapper import wrap
4 | from logger import logger
5 | from .__version__ import __version__
6 | from utils import db_model as utils
7 |
8 |
9 |
10 | def is_allow_access(chat_id) -> bool:
11 | '''
12 | 检查当前chat_id有权限使用bot
13 |
14 | Args:
15 | chat_id (_type_): Telegram chat id
16 |
17 | Returns:
18 | bool: 是否允许使用
19 | '''
20 | # 非公共服务
21 | if 'private_service' in config and config['private_service']:
22 | if 'authorized_users' in config:
23 | # 只服务指定的用户
24 | if chat_id in config['authorized_users']:
25 | return True
26 | return False
27 | return True
28 |
29 | def read_tag_from_file(filename="version.txt"):
30 | '''
31 | 获取tag信息
32 | Args:
33 | filename (str, optional): _description_. Defaults to "version.txt".
34 |
35 | Returns:
36 | _type_: _description_
37 | '''
38 | return __version__
39 | # try:
40 | # with open(filename, "r") as f:
41 | # tag = f.read().strip()
42 | # except FileNotFoundError:
43 | # tag = "unknown"
44 | # return tag
45 |
46 | @wrap(border_string='##',min_padding=2)
47 | def banner():
48 | init() # 初始化colorama
49 | green_circle = f"{Fore.GREEN}● success{Style.RESET_ALL}\n"
50 | tag = read_tag_from_file()
51 | message = f"{green_circle} 🤖️Telegram keyword alert bot (Version: {tag})"
52 | return message
53 |
54 |
55 | def is_msg_block(receiver,msg,channel_name,channel_id):
56 | """
57 | 消息黑名单检查
58 | Args:
59 | receiver : 消息接收用户 chat id
60 | msg : 消息内容
61 | channel_name : 消息发送的频道名称
62 | channel_id : 消息发送的频道id
63 |
64 | Returns:
65 | Bool: True 命中黑名单 不发送消息,False 无命中 发送消息
66 | """
67 | user = utils.db.user.get_or_none(chat_id=receiver)
68 |
69 | for blacklist_type in ['length_limit']:
70 | find = utils.db.connect.execute_sql('select id,blacklist_value from user_block_list where user_id = ? and blacklist_type=? ' ,(user.id,blacklist_type)).fetchone()
71 | if find:
72 | (id,blacklist_value) = find
73 | if blacklist_type == 'length_limit':
74 | limit = int(blacklist_value)
75 | msg_len = len(msg)
76 | if limit and msg_len > limit:
77 | logger.info(f'block_list_check refuse send. blacklist_type: {blacklist_type}, limit: {limit}, msg_len: {msg_len}')
78 | return True
79 | return False
80 |
81 |
82 | def get_event_chat_username(event_chat):
83 | '''
84 | 获取群组/频道的单个用户名
85 | 2023-05-25 发现群组存在多用户名的情况,只在usernames属性中有值
86 | '''
87 |
88 | if hasattr(event_chat,'username') and event_chat.username:
89 | return event_chat.username
90 |
91 | if hasattr(event_chat,'usernames') and event_chat.usernames:
92 | standby_username = ''# 备选用户名
93 | for i in event_chat.usernames:
94 | if i.active and not i.editable and i.username:# 激活的用户名且不可编辑.优先读取
95 | return i.username
96 | if i.active and i.username:# 激活的用户名且不可编辑.备选读取
97 | standby_username = i.username
98 |
99 | if standby_username:
100 | return standby_username
101 |
102 | return None
103 |
104 |
105 | def get_event_chat_username_list(event_chat):
106 | '''
107 | 获取群组/频道的所有用户名列表
108 | '''
109 | result = []
110 | if hasattr(event_chat,'username') and event_chat.username:
111 | result.append(event_chat.username)
112 |
113 | if hasattr(event_chat,'usernames') and event_chat.usernames:
114 | for i in event_chat.usernames:
115 | if i.active and i.username:# 激活的用户名
116 | result.append(i.username)
117 |
118 | return list(set(result))
119 |
120 |
121 | def build_sublist_msg(subscribeid,keywords_type,keywords,channel_url,channel_title = '',channel_username = ''):
122 | msg = f'ID: {subscribeid}\n{keywords_type.capitalize()}: {keywords}\nChannel: {" ".join([channel_title,channel_username,channel_url]).strip()}\n{"---"*12}\n'
123 | return msg
124 |
--------------------------------------------------------------------------------
/utils/db_model.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | """
3 | 数据库操作类
4 | """
5 | import logging,sys,os,datetime
6 | import re
7 | from peewee import MySQLDatabase,BigIntegerField,Model,CharField,DoubleField,IntegerField,CharField,SqliteDatabase,FloatField,SmallIntegerField,DateTimeField
8 | from peewee import OperationalError
9 |
10 | __all__ = [
11 | 'db',
12 | 'User',
13 | 'User_subscribe_list',
14 | 'User_block_list',
15 | ]
16 |
17 | # 获取项目根目录
18 | _root_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
19 | # 数据库路径设置为项目根目录下的db目录
20 | _path = '{}/db/.db'.format(_root_path)
21 | _path_dir = os.path.dirname(_path)
22 | not os.path.exists(_path_dir) and os.makedirs(_path_dir)
23 |
24 | # 本地 执行sqlite写入
25 | _connect = SqliteDatabase(_path)
26 |
27 | _connect.is_closed() and _connect.connect()
28 |
29 | class _Base(Model):
30 | # #将表和数据库连接
31 | class Meta:
32 | database = _connect
33 |
34 | class User(_Base):
35 | """用户数据表
36 | id chat_id create_time
37 | """
38 | chat_id = IntegerField(index=True,unique=True)
39 | create_time = DateTimeField('%Y-%m-%d %H:%M:%S',index=True)
40 |
41 | class Meta:
42 | indexes = (
43 | # (('字段1', '字段2'), True), # 字段1与字段2整体作为索引,True 代表唯一索引
44 | # (('字段1', '字段2'), False), # 字段1与字段2整体作为索引,False 代表普通索引
45 | # (('price','type','time'), False), # 联合索引
46 | )
47 |
48 | class User_subscribe_list(_Base):
49 | """
50 | 用户订阅表
51 | user_subscribe_list
52 | id user_id channel_name keywords status create_time
53 | """
54 | user_id = IntegerField(index=True)
55 | channel_name = CharField(50,null=False)# 频道名称
56 |
57 | # https://docs.telethon.dev/en/latest/concepts/chats-vs-channels.html#channels
58 | chat_id = CharField(50,null=False,default='')# 频道的非官方id。 e.g. -1001630956637
59 |
60 | keywords = CharField(120,null=False)#
61 | status = SmallIntegerField(default=0)# 0 正常 1删除
62 | create_time = DateTimeField('%Y-%m-%d %H:%M:%S',null=True)
63 |
64 | class User_block_list(_Base):
65 | """
66 | 用户屏蔽列表(黑名单设置)
67 | user_block_list
68 | id user_id blacklist_type blacklist_value channel_name chat_id create_time update_time
69 | """
70 | user_id = IntegerField(index=True)
71 |
72 | blacklist_type = CharField(50, null=False) # 黑名单的类型。比如length_limit、keyword、username
73 | blacklist_value = CharField(120, null=False) # 黑名单值
74 |
75 | channel_name = CharField(50,null=True,default='')# 应用范围 频道名称
76 | chat_id = CharField(50, null=True, default='') # 应用范围 群组/频道的非官方id。 e.g. -1001630956637,如果为空或默认值,表示所有群组
77 |
78 | create_time = DateTimeField('%Y-%m-%d %H:%M:%S', null=True)
79 | update_time = DateTimeField('%Y-%m-%d %H:%M:%S', null=True)
80 |
81 | class Meta:
82 | indexes = (
83 | # (('user_id', 'channel_name','chat_id', 'blocked_username'), True), # user_id, chat_id和blocked_username整体作为唯一索引
84 | )
85 |
86 | class _Db:
87 | def __init__(self):
88 | #创建实例类
89 | init_class = [
90 | User,
91 | User_subscribe_list,
92 | User_block_list,
93 | ]
94 | for model_class in init_class:
95 | try:
96 | model = model_class()
97 | model.table_exists() or (model.create_table()) #不存在 则创建表
98 |
99 | # 执行空查询(检测字段缺失的报错 )
100 | model.get_or_none(0)
101 |
102 | setattr(self,model_class.__name__.lower(),model)
103 | except OperationalError as __e:
104 | _e = str(__e)
105 |
106 | # 处理字段不存在的报错
107 | if 'no such column' in _e:
108 | find = re.search('no such column: (?:\w+\.)([a-z_0-9]+)$',_e)
109 | if find:
110 | field = find.group(1)
111 | if hasattr(model_class,field):
112 | self.add_column(model_class.__name__.lower(),getattr(model_class,field))
113 | else:
114 | raise __e
115 |
116 | def add_column(slef,table,field):
117 | '''
118 | 动态添加字段
119 |
120 | https://stackoverflow.com/questions/35012012/peewee-adding-columns-on-demand
121 |
122 | Args:
123 | slef ([type]): [description]
124 | table ([type]): [description]
125 | field ([type]): [description]
126 | '''
127 | from playhouse.migrate import SqliteMigrator,migrate
128 | migrator = SqliteMigrator(_connect)
129 | migrate(
130 | migrator.add_column(table, field.name, field),
131 | )
132 |
133 |
134 | def __del__(self):
135 | # logger.debug('db connect close')
136 | # _connect.close()
137 | pass
138 |
139 | db = _Db()
140 | db.connect = _connect
141 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 🤖Telegram keyword alert bot⏰
3 |
4 | 
5 | [](https://www.python.org/)
6 | [](https://github.com/Hootrix/keyword_alert_bot/blob/master/LICENSE)
7 | [](https://www.paypal.com/donate/?business=DRVVDHMVL8G7Q&no_recurring=0&item_name=Sponsored+development+of+keyword_alert_bot%21+¤cy_code=USD)
8 | [](https://github.com/sponsors/Hootrix)
9 |
10 | Telegram关键字提醒机器人,用于实时监测频道/群组中的关键字消息。
11 |
12 | 确保普通Telegram账户能够在不需要验证的情况下加入指定群组。
13 |
14 | Warning: Demo bot使用过载,建议使用 Docker 镜像自部署
15 |
16 |
17 | 👉 Features:
18 |
19 | - [x] 关键字消息订阅:根据设定的关键字和频道实时推送消息提醒
20 | - [x] 支持正则表达式匹配语法
21 | - [x] 支持多频道订阅 & 多关键字订阅
22 | - [x] 支持订阅群组消息
23 | - [x] 支持私有频道ID/邀请链接的消息订阅
24 | - [x] 支持私有群组订阅
25 |
26 | 1. https://t.me/+B8yv7lgd9FI0Y2M1
27 | 2. https://t.me/joinchat/B8yv7lgd9FI0Y2M1
28 |
29 |
30 | 👉 Todo:
31 |
32 | - [ ] 私有频道消息提醒完整内容预览
33 | - [ ] 多账号支持
34 | - [ ] 扫描退出无用频道/群组
35 |
36 | ## 🔍Demo
37 |
38 | http://t.me/keyword_alert_bot
39 |
40 |
41 |
42 |
43 | ## 🚀Run
44 |
45 | ### 1. 配置文件
46 |
47 | #### config.yml.example --> config.yml
48 |
49 | 将 config.yml.example 复制到本地并重命名为 config.yml,然后根据下面申请的 api 进行配置
50 |
51 | #### Create Telelgram Account & API
52 |
53 | 建议使用新Telegram账户[开通api](https://my.telegram.org/apps) 来使用
54 |
55 | #### Create BOT
56 |
57 | https://t.me/BotFather 创建机器人
58 |
59 |
60 | ### 2. 🐳Docker
61 |
62 | ```
63 | $ docker run -it --name keyword_alert_bot -v $(pwd)/config.yml:/app/config.yml -v $(pwd)/db/:/app/db/ yha8897/keyword_alert_bot
64 |
65 | Please enter the code you received: 12345
66 | Please enter your password:
67 | Signed in successfully as DEMO; remember to not break the ToS or you will risk an account ban!
68 |
69 | #################################################################
70 | ## ##
71 | ## ● success ##
72 | ## 🤖️Telegram keyword alert bot (Version: 20240627.f6672cf) ##
73 | ## ##
74 | #################################################################
75 |
76 | ```
77 |
78 | 首次运行需要Telegram账户接收数字验证码,并输入密码(Telegram API触发),之后提示success即可
79 |
80 |
81 | 其他
82 | ```
83 | # 重启
84 | $ docker restart keyword_alert_bot
85 |
86 | # 停止
87 | $ docker stop keyword_alert_bot
88 |
89 | # 数据库文件挂载路径: /app/db/.db
90 | $ docker run -it --name keyword_alert_bot -v $(pwd)/config.yml:/app/config.yml -v $(pwd)/db/keyword_alert_bot.db:/app/db/.db yha8897/keyword_alert_bot
91 |
92 | ```
93 |
94 | ### docker镜像更新
95 |
96 | 避免数据丢失,容器更新前记得把docker中数据备份。如果已经把数据库文件挂载进容器 可以不用
97 | ```
98 | $ docker cp keyword_alert_bot:/app/db/.db ~/keyword_alert_bot.db
99 | # 即可保存到: ~/keyword_alert_bot.db
100 | ```
101 |
102 | 持久化所有数据,避免权限问题 `--user root` 强制root权限执行
103 | ```
104 | $ docker run -d --name keyword_alert_bot --user root -v $(pwd)/config.yml:/app/config.yml -v $(pwd)/db/:/app/db/ -v $(pwd)/.tmp/:/app/.tmp/ -v $(pwd)/logs/:/app/logs/ yha8897/keyword_alert_bot
105 | ```
106 |
107 | ## 💪Manual Build
108 |
109 | 运行环境 python3.7+
110 |
111 |
112 | ```
113 | $ pipenv install
114 |
115 | $ pipenv shell
116 |
117 | $ python3 ./main.py
118 | ```
119 |
120 |
121 | ## 📘Usage
122 |
123 | ### 普通关键字匹配
124 |
125 | ```
126 | /subscribe 免费 https://t.me/tianfutong
127 | /subscribe 优惠券 https://t.me/tianfutong
128 |
129 | ```
130 |
131 | ### 正则表达式匹配
132 |
133 | 使用类似JavaScript正则语法规则,用/包裹正则语句,目前可以使用的匹配模式:i,g
134 |
135 | ```
136 | # 订阅手机型号关键字:iphone x,排除XR,XS等型号,且忽略大小写
137 | /subscribe /(iphone\s*x)(?:[^sr]|$)/ig com9ji,xiaobaiup
138 | /subscribe /(iphone\s*x)(?:[^sr]|$)/ig https://t.me/com9ji,https://t.me/xiaobaiup
139 |
140 | # xx券
141 | /subscribe /([\S]{2}券)/g https://t.me/tianfutong
142 |
143 | ```
144 |
145 |
146 |
147 | ## Q & A
148 |
149 | > Bug Feedback: https://github.com/Hootrix/keyword_alert_bot/issues
150 |
151 |
152 | ### 1. You have joined too many channels/supergroups (caused by JoinChannelRequest)
153 |
154 | BOT中所有订阅频道的总数超过 500。原因是BOT使用的Telegram演示账户限制导致。建议你自行部署
155 |
156 | ### 2. sqlite3.OperationalError: unable to open database file
157 |
158 | 如果是docker镜像启动,由于内部使用nonroot账户 需要授权挂载文件权限 或者直接使用`--user root`参数
159 | ```
160 | $ docker run -it --name keyword_alert_bot --user root -v $(pwd)/config.yml:/app/config.yml -v $(pwd)/db/:/app/db/ -v $(pwd)/.tmp/:/app/.tmp/ -v $(pwd)/logs/:/app/logs/ yha8897/keyword_alert_bot
161 | ```
162 |
163 |
164 | ### 3. 查看日志发现个别群组无法接收消息,而软件客户端正常接收
165 |
166 | 🤔尝试更新telethon到最新版本或者稳定的1.24.0版本
167 |
168 | ### 4. 订阅群组消息,机器人没任何反应
169 | https://github.com/Hootrix/keyword_alert_bot/issues/20
170 |
171 | ### 5. 同时存在多关键字如何匹配
172 |
173 | ```
174 | /(?=.*cc)(?=.*bb)(?=.*aa).*/
175 | ```
176 |
177 |
178 | ## ☕ Buy me a coffee
179 |
180 | [USDT-TRC20]:`TDELNhqYjMJvrChjcTBiBBieWYiDGiGm2r`
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
--------------------------------------------------------------------------------
/Pipfile.lock:
--------------------------------------------------------------------------------
1 | {
2 | "_meta": {
3 | "hash": {
4 | "sha256": "fcef63f631801c162871ba4ea7a4715a6da57eb837ea7f65c793170f4655c81c"
5 | },
6 | "pipfile-spec": 6,
7 | "requires": {
8 | "python_version": "3.11"
9 | },
10 | "sources": [
11 | {
12 | "name": "pypi",
13 | "url": "https://pypi.org/simple",
14 | "verify_ssl": true
15 | }
16 | ]
17 | },
18 | "default": {
19 | "asyncstdlib": {
20 | "hashes": [
21 | "sha256:e18b67de483dfbfec3c17ec2121a8a3fa9b950874ff03802819bd3b1af56148f",
22 | "sha256:eb0dbc697a238fe1ef141e29b3396ead816aaf8a28f07e584e05d1d9fb26841a"
23 | ],
24 | "index": "pypi",
25 | "version": "==3.10.8"
26 | },
27 | "colorama": {
28 | "hashes": [
29 | "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44",
30 | "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"
31 | ],
32 | "index": "pypi",
33 | "version": "==0.4.6"
34 | },
35 | "diskcache": {
36 | "hashes": [
37 | "sha256:558c6a2d5d7c721bb00e40711803d6804850c9f76c426ed81ecc627fe9d2ce2d",
38 | "sha256:e4c978532feff5814c4cc00fe1e11e40501985946643d73220d41ee7737c72c3"
39 | ],
40 | "index": "pypi",
41 | "version": "==5.6.1"
42 | },
43 | "peewee": {
44 | "hashes": [
45 | "sha256:12b30e931193bc37b11f7c2ac646e3f67125a8b1a543ad6ab37ad124c8df7d16"
46 | ],
47 | "index": "pypi",
48 | "version": "==3.16.3"
49 | },
50 | "pyaes": {
51 | "hashes": [
52 | "sha256:02c1b1405c38d3c370b085fb952dd8bea3fadcee6411ad99f312cc129c536d8f"
53 | ],
54 | "version": "==1.6.1"
55 | },
56 | "pyasn1": {
57 | "hashes": [
58 | "sha256:87a2121042a1ac9358cabcaf1d07680ff97ee6404333bacca15f76aa8ad01a57",
59 | "sha256:97b7290ca68e62a832558ec3976f15cbf911bf5d7c7039d8b861c2a0ece69fde"
60 | ],
61 | "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4, 3.5'",
62 | "version": "==0.5.0"
63 | },
64 | "pysocks": {
65 | "hashes": [
66 | "sha256:08e69f092cc6dbe92a0fdd16eeb9b9ffbc13cadfe5ca4c7bd92ffb078b293299",
67 | "sha256:2725bd0a9925919b9b51739eea5f9e2bae91e83288108a9ad338b2e3a4435ee5",
68 | "sha256:3f8804571ebe159c380ac6de37643bb4685970655d3bba243530d6558b799aa0"
69 | ],
70 | "index": "pypi",
71 | "version": "==1.7.1"
72 | },
73 | "pyyaml": {
74 | "hashes": [
75 | "sha256:062582fca9fabdd2c8b54a3ef1c978d786e0f6b3a1510e0ac93ef59e0ddae2bc",
76 | "sha256:1635fd110e8d85d55237ab316b5b011de701ea0f29d07611174a1b42f1444741",
77 | "sha256:184c5108a2aca3c5b3d3bf9395d50893a7ab82a38004c8f61c258d4428e80206",
78 | "sha256:18aeb1bf9a78867dc38b259769503436b7c72f7a1f1f4c93ff9a17de54319b27",
79 | "sha256:1d4c7e777c441b20e32f52bd377e0c409713e8bb1386e1099c2415f26e479595",
80 | "sha256:1e2722cc9fbb45d9b87631ac70924c11d3a401b2d7f410cc0e3bbf249f2dca62",
81 | "sha256:1fe35611261b29bd1de0070f0b2f47cb6ff71fa6595c077e42bd0c419fa27b98",
82 | "sha256:28c119d996beec18c05208a8bd78cbe4007878c6dd15091efb73a30e90539696",
83 | "sha256:42f8152b8dbc4fe7d96729ec2b99c7097d656dc1213a3229ca5383f973a5ed6d",
84 | "sha256:4fb147e7a67ef577a588a0e2c17b6db51dda102c71de36f8549b6816a96e1867",
85 | "sha256:50550eb667afee136e9a77d6dc71ae76a44df8b3e51e41b77f6de2932bfe0f47",
86 | "sha256:510c9deebc5c0225e8c96813043e62b680ba2f9c50a08d3724c7f28a747d1486",
87 | "sha256:5773183b6446b2c99bb77e77595dd486303b4faab2b086e7b17bc6bef28865f6",
88 | "sha256:596106435fa6ad000c2991a98fa58eeb8656ef2325d7e158344fb33864ed87e3",
89 | "sha256:6965a7bc3cf88e5a1c3bd2e0b5c22f8d677dc88a455344035f03399034eb3007",
90 | "sha256:69b023b2b4daa7548bcfbd4aa3da05b3a74b772db9e23b982788168117739938",
91 | "sha256:704219a11b772aea0d8ecd7058d0082713c3562b4e271b849ad7dc4a5c90c13c",
92 | "sha256:7e07cbde391ba96ab58e532ff4803f79c4129397514e1413a7dc761ccd755735",
93 | "sha256:81e0b275a9ecc9c0c0c07b4b90ba548307583c125f54d5b6946cfee6360c733d",
94 | "sha256:9046c58c4395dff28dd494285c82ba00b546adfc7ef001486fbf0324bc174fba",
95 | "sha256:9eb6caa9a297fc2c2fb8862bc5370d0303ddba53ba97e71f08023b6cd73d16a8",
96 | "sha256:a0cd17c15d3bb3fa06978b4e8958dcdc6e0174ccea823003a106c7d4d7899ac5",
97 | "sha256:afd7e57eddb1a54f0f1a974bc4391af8bcce0b444685d936840f125cf046d5bd",
98 | "sha256:b1275ad35a5d18c62a7220633c913e1b42d44b46ee12554e5fd39c70a243d6a3",
99 | "sha256:b786eecbdf8499b9ca1d697215862083bd6d2a99965554781d0d8d1ad31e13a0",
100 | "sha256:ba336e390cd8e4d1739f42dfe9bb83a3cc2e80f567d8805e11b46f4a943f5515",
101 | "sha256:baa90d3f661d43131ca170712d903e6295d1f7a0f595074f151c0aed377c9b9c",
102 | "sha256:bc1bf2925a1ecd43da378f4db9e4f799775d6367bdb94671027b73b393a7c42c",
103 | "sha256:bd4af7373a854424dabd882decdc5579653d7868b8fb26dc7d0e99f823aa5924",
104 | "sha256:bf07ee2fef7014951eeb99f56f39c9bb4af143d8aa3c21b1677805985307da34",
105 | "sha256:bfdf460b1736c775f2ba9f6a92bca30bc2095067b8a9d77876d1fad6cc3b4a43",
106 | "sha256:c8098ddcc2a85b61647b2590f825f3db38891662cfc2fc776415143f599bb859",
107 | "sha256:d2b04aac4d386b172d5b9692e2d2da8de7bfb6c387fa4f801fbf6fb2e6ba4673",
108 | "sha256:d858aa552c999bc8a8d57426ed01e40bef403cd8ccdd0fc5f6f04a00414cac2a",
109 | "sha256:f003ed9ad21d6a4713f0a9b5a7a0a79e08dd0f221aff4525a2be4c346ee60aab",
110 | "sha256:f22ac1c3cac4dbc50079e965eba2c1058622631e526bd9afd45fedd49ba781fa",
111 | "sha256:faca3bdcf85b2fc05d06ff3fbc1f83e1391b3e724afa3feba7d13eeab355484c",
112 | "sha256:fca0e3a251908a499833aa292323f32437106001d436eca0e6e7833256674585",
113 | "sha256:fd1592b3fdf65fff2ad0004b5e363300ef59ced41c2e6b3a99d4089fa8c5435d",
114 | "sha256:fd66fc5d0da6d9815ba2cebeb4205f95818ff4b79c3ebe268e75d961704af52f"
115 | ],
116 | "index": "pypi",
117 | "version": "==6.0.1"
118 | },
119 | "rsa": {
120 | "hashes": [
121 | "sha256:90260d9058e514786967344d0ef75fa8727eed8a7d2e43ce9f4bcf1b536174f7",
122 | "sha256:e38464a49c6c85d7f1351b0126661487a7e0a14a50f1675ec50eb34d4f20ef21"
123 | ],
124 | "markers": "python_version >= '3.6' and python_version < '4'",
125 | "version": "==4.9"
126 | },
127 | "telethon": {
128 | "hashes": [
129 | "sha256:cac3091ab61bdd2286bdfb72fb3ab7cc86a9e8d3327ff8fec56d215e05009e1e"
130 | ],
131 | "index": "pypi",
132 | "version": "===1.29.3"
133 | },
134 | "text-box-wrapper": {
135 | "hashes": [
136 | "sha256:4443678cd7bfb06dee4d3a243ce73e2adba07570f660369a5634d6966c5daf18",
137 | "sha256:675b55073b0caa7475369880a74716f132d6fe0cbbf845f336f449a44807c414"
138 | ],
139 | "index": "pypi",
140 | "version": "==0.1.5"
141 | },
142 | "wcwidth": {
143 | "hashes": [
144 | "sha256:795b138f6875577cd91bba52baf9e445cd5118fd32723b460e30a0af30ea230e",
145 | "sha256:a5220780a404dbe3353789870978e472cfe477761f06ee55077256e509b156d0"
146 | ],
147 | "version": "==0.2.6"
148 | }
149 | },
150 | "develop": {}
151 | }
152 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | from telethon import TelegramClient, events, sync, errors
3 | import socks,os,datetime
4 | import re as regex
5 | import diskcache
6 | import time
7 | from urllib.parse import urlparse
8 | from telethon.tl.functions.channels import JoinChannelRequest
9 | from telethon.tl.functions.messages import ImportChatInviteRequest
10 | from telethon.tl.functions.messages import CheckChatInviteRequest
11 | from telethon.tl.functions.channels import DeleteHistoryRequest
12 | from telethon.tl.functions.channels import LeaveChannelRequest, DeleteChannelRequest
13 | from logger import logger
14 | from config import config,_current_path as current_path
15 | from telethon import utils as telethon_utils
16 | from telethon.tl.types import PeerChannel
17 | from telethon.extensions import markdown,html
18 | from asyncstdlib.functools import lru_cache as async_lru_cache
19 | import asyncio
20 | from utils.common import is_allow_access,banner,is_msg_block,get_event_chat_username,get_event_chat_username_list,build_sublist_msg
21 | from utils import db_model as utils
22 |
23 |
24 | # 配置访问tg服务器的代理
25 | proxy = None
26 | if all(config['proxy'].values()): # 同时不为None
27 | logger.info(f'proxy info:{config["proxy"]}')
28 | proxy = (getattr(socks,config['proxy']['type']), config['proxy']['address'], config['proxy']['port'])
29 | # proxy = (socks.SOCKS5, '127.0.0.1', 1088)
30 |
31 | account = config['account']
32 | account['bot_name'] = account.get('bot_name') or account['bot_username']
33 | tmp_path = f'{current_path}/.tmp/'
34 | cache = diskcache.Cache(tmp_path)# 设置缓存文件目录 当前tmp文件夹。用于缓存分步执行命令的操作,避免bot无法找到当前输入操作的进度
35 | client = TelegramClient(f'{tmp_path}/.{account["username"]}_tg_login', account['api_id'], account['api_hash'], proxy = proxy)
36 | client.start(phone=account['phone'])
37 | # client.start()
38 |
39 | # 设置bot,且直接启动
40 | bot = TelegramClient(f'{tmp_path}/.{account["bot_name"]}', account['api_id'], account['api_hash'],proxy = proxy).start(bot_token=account['bot_token'])
41 |
42 | def js_to_py_re(rx):
43 | '''
44 | 解析js的正则字符串到python中使用
45 | 只支持ig两个匹配模式
46 | '''
47 | query, params = rx[1:].rsplit('/', 1)
48 | if 'g' in params:
49 | obj = regex.findall
50 | else:
51 | obj = regex.search
52 |
53 | # May need to make flags= smarter, but just an example...
54 | return lambda L: obj(query, L, flags=regex.I if 'i' in params else 0)
55 |
56 | def is_regex_str(string):
57 | """
58 | 正则表达式严格校验
59 | :param rule: 输入规则字符串
60 | :return: True 如果为合法正则语法
61 | """
62 | # return regex.search(r'^/.*/[a-zA-Z]*?$',string)
63 | try:
64 | query, params = string[1:].rsplit('/', 1)
65 | if query:
66 | regex.compile(query) # 编译正则表达式
67 | return True
68 | except:
69 | return False
70 |
71 | return False
72 |
73 | def is_regex_str_fuzzy(rule):
74 | return is_regex_str(rule)
75 | # match = regex.fullmatch(r"^/(.+)/([a-zA-Z]*)$", rule)
76 | # return bool(match)
77 |
78 | @async_lru_cache(maxsize=None)
79 | async def client_get_entity(entity,_):
80 | '''
81 | 读取频道信息
82 | client.get_entity 内存缓存替代方法
83 |
84 | 尽量避免get_entity出现频繁请求报错
85 | A wait of 19964 seconds is required (caused by ResolveUsernameRequest)
86 |
87 | Args:
88 | entity (_type_): 同get_entity()参数
89 | _ (_type_): lru缓存标记值
90 |
91 | Example:
92 | 缓存 1天
93 | await client_get_entity(real_id, time.time() // 86400 )
94 |
95 | 缓存 10秒
96 | await client_get_entity(real_id, time.time() // 10 )
97 |
98 | Returns:
99 | Entity:
100 | '''
101 | return await client.get_entity(entity)
102 |
103 |
104 |
105 | async def cache_set(*args):
106 | '''
107 | 缓存写入 异步方式
108 |
109 | wiki:https://github.com/grantjenks/python-diskcache/commit/dfad0aa27362354901d90457e465b8b246570c3e
110 |
111 | Returns:
112 | _type_: _description_
113 | '''
114 | loop = asyncio.get_running_loop()
115 | future = loop.run_in_executor(None, cache.set, *args)
116 | result = await future
117 | return result
118 |
119 | async def cache_get(*args):
120 | loop = asyncio.get_running_loop()
121 | future = loop.run_in_executor(None, cache.get, *args)
122 | result = await future
123 | return result
124 |
125 | async def resolve_invit_hash(invit_hash,expired_secends = 60 * 5):
126 | '''
127 | 解析邀请链接 https://t.me/+G-w4Ovfzp9U4YTFl
128 | 默认缓存5min
129 |
130 | Args:
131 | invite_hash (str): e.g. G-w4Ovfzp9U4YTFl
132 | expired_secends (int): None: not cache , 60: 1min
133 |
134 | Returns:
135 | Tuple | None: (marked_id,chat_title)
136 | '''
137 | if not invit_hash: return None
138 | marked_id = ''
139 | chat_title = ''
140 |
141 | cache_key = f'01211resolve_invit_hash{invit_hash}'
142 | find = await cache_get(cache_key)
143 | if find:
144 | logger.info(f'resolve_invit_hash HIT CACHE: {invit_hash}')
145 | return find
146 |
147 | logger.info(f'resolve_invit_hash MISS: {invit_hash}')
148 | chatinvite = await client(CheckChatInviteRequest(invit_hash))
149 | if chatinvite and hasattr(chatinvite,'chat'):# 已加入
150 | # chatinvite.chat.id # 1695903641
151 | # chatinvite.chat.title # '测试'
152 |
153 | marked_id = telethon_utils.get_peer_id(PeerChannel(chatinvite.chat.id)) # 转换为marked_id
154 | chat_title = chatinvite.chat.title
155 | channel_entity = chatinvite.chat
156 | rel = (marked_id,chat_title,channel_entity)
157 | await cache_set(cache_key,rel,expired_secends)
158 | # cache.set(cache_key,rel,expired_secends)
159 | return rel
160 | return None
161 |
162 | # client相关操作 目的:读取消息
163 | @client.on(events.MessageEdited)
164 | @client.on(events.NewMessage())
165 | async def on_greeting(event):
166 | '''Greets someone'''
167 | # telethon.events.newmessage.NewMessage.Event
168 | # telethon.events.messageedited.MessageEdited.Event
169 | if not event.chat: # 私有群组出现None
170 | channel_entity = await client_get_entity(event.chat_id,None)
171 | if channel_entity:
172 | event_chat = channel_entity
173 | setattr(event_chat,'username','')
174 | else:
175 | logger.error(f'event_chat empty. event: { event }')
176 | raise events.StopPropagation
177 | else:
178 | event_chat = event.chat
179 |
180 | if not hasattr(event_chat,'username'):
181 | logger.error(f'event_chat not found username:{event_chat}')
182 | raise events.StopPropagation
183 |
184 | if event_chat.username == account['bot_name']: # 不监听当前机器人消息
185 | logger.debug(f'不监听当前机器人消息, event_chat.username: { event_chat.username }')
186 | raise events.StopPropagation
187 |
188 | # 是否拒绝来自其它机器人发在群里的消息
189 | if 'block_bot_msg' in config and config['block_bot_msg']:
190 | if hasattr(event.message.sender,'bot') and event.message.sender.bot :
191 | logger.debug(f'不监听所有机器人消息, event_chat.username: { event_chat.username }')
192 | raise events.StopPropagation
193 |
194 | # if not event.is_group:# channel 类型
195 | if True:# 所有消息类型,支持群组
196 | message = event.message
197 |
198 | text = message.text
199 | if message.file and message.file.name:
200 | # text += ' file:{}'.format(message.file.name)# 追加上文件名
201 | text += ' {}'.format(message.file.name)# 追加上文件名
202 |
203 | # 打印消息
204 | _title = ''
205 | if not hasattr(event_chat,'title'):
206 | logger.warning(f'event_chat not found title:{event_chat}')
207 | else:
208 | _title = f'event.chat.title:{event_chat.title},'
209 | logger.debug(f'event.chat.username: {get_event_chat_username(event_chat)},event.chat.id:{event_chat.id},{_title} event.message.id:{event.message.id},text:{text}')
210 |
211 | # 1.方法(失败):转发消息
212 | # chat = 'keyword_alert_bot' #能转发 但是不能真对特定用户。只能转发给当前允许账户的bot
213 | # from_chat = 'tianfutong'
214 | # chat = 349506543# 无法使用chat_id直接转发 没有任何反应
215 | # chat = 1354871670
216 | # await message.forward_to('keyword_alert_bot')
217 | # await client.forward_messages(chat, message)
218 | # await bot.forward_messages(chat, message)
219 | # await client.forward_messages(chat, message.id, from_chat)
220 |
221 | # 2.方法:直接发送新消息,非转发.但是可以url预览达到效果
222 |
223 | # 查找当前频道的所有订阅
224 | event_chat_username_list = get_event_chat_username_list(event_chat)
225 | event_chat_username = get_event_chat_username(event_chat)
226 | placeholders = ','.join('?' for _ in event_chat_username_list)# 占位符填充
227 |
228 | condition_strs = ['l.chat_id = ?']
229 | if event_chat_username_list:
230 | condition_strs.append(f' l.channel_name in ({placeholders}) ')
231 |
232 | sql = f"""
233 | select u.chat_id,l.keywords,l.id,l.chat_id
234 | from user_subscribe_list as l
235 | INNER JOIN user as u on u.id = l.user_id
236 | where ({' OR '.join(condition_strs)}) and l.status = 0 order by l.create_time desc
237 | """
238 |
239 | # bind = [str(event.chat_id)]
240 | bind = [str(telethon_utils.get_peer_id(PeerChannel(event.chat_id)))] # 确保查询和入库的id单位统一 marked_id
241 | if event_chat_username_list:
242 | bind += event_chat_username_list
243 |
244 | find = utils.db.connect.execute_sql(sql,tuple(bind)).fetchall()
245 | if find:
246 | logger.info(f'channel: {event_chat_username_list}; all chat_id & keywords:{find}') # 打印当前频道,订阅的用户以及关键字
247 |
248 | for receiver,keywords,l_id,l_chat_id in find:
249 | try:
250 | # 消息发送去重规则
251 | MSG_UNIQUE_RULE_MAP = {
252 | 'SUBSCRIBE_ID': f'{receiver}_{l_id}',
253 | 'MESSAGE_ID': f'{receiver}_{message.id}',
254 | }
255 | if 'msg_unique_rule' not in config:
256 | config['msg_unique_rule'] = 'SUBSCRIBE_ID'
257 | assert config['msg_unique_rule'] in MSG_UNIQUE_RULE_MAP,'config "msg_unique_rule" error!!!'
258 | CACHE_KEY_UNIQUE_SEND = MSG_UNIQUE_RULE_MAP[config['msg_unique_rule']]
259 | logger.debug(f'msg_unique_rule:{config["msg_unique_rule"]} --> {CACHE_KEY_UNIQUE_SEND}')
260 |
261 | # 优先返回可预览url
262 | channel_url = f'https://t.me/{event_chat_username}/' if event_chat_username else get_channel_url(event_chat_username,event.chat_id)
263 |
264 | channel_msg_url= f'{channel_url}{message.id}'
265 | send_cache_key = f'_LAST_{l_id}_{message.id}_send'
266 | if isinstance(event,events.MessageEdited.Event):# 编辑事件
267 | # 24小时内新建2秒后的编辑不提醒
268 | if cache.get(send_cache_key) and (event.message.edit_date - event.message.date) > datetime.timedelta(seconds=2):
269 | logger.error(f'{channel_msg_url} repeat send. deny!')
270 | continue
271 | if not l_chat_id:# 未记录频道id
272 | logger.info(f'update user_subscribe_list.chat_id:{event.chat_id} where id = {l_id} ')
273 | re_update = utils.db.user_subscribe_list.update(chat_id = str(event.chat_id) ).where(utils.User_subscribe_list.id == l_id)
274 | re_update.execute()
275 |
276 | chat_title = event_chat_username or event.chat.title
277 | if is_regex_str_fuzzy(keywords):# 输入为正则字符串
278 | regex_match = js_to_py_re(keywords)(text)# 进行正则匹配 只支持ig两个flag
279 | if isinstance(regex_match,regex.Match):#search()结果
280 | regex_match = [regex_match.group()]
281 | regex_match_str = []# 显示内容
282 | for _ in regex_match:
283 | item = ''.join(_) if isinstance(_,tuple) else _
284 | if item:
285 | regex_match_str.append(item) # 合并处理掉空格
286 | regex_match_str = list(set(regex_match_str))# 处理重复元素
287 | if regex_match_str:# 默认 findall()结果
288 | # # {chat_title} \n\n
289 | channel_title = f"\n\nCHANNEL: {chat_title}" if not event_chat_username else ""
290 |
291 | message_str = f'[#FOUND]({channel_msg_url}) **{regex_match_str}**{channel_title}'
292 | if cache.add(CACHE_KEY_UNIQUE_SEND,1,expire=5):
293 | logger.info(f'REGEX: receiver chat_id:{receiver}, l_id:{l_id}, message_str:{message_str}')
294 | if isinstance(event,events.NewMessage.Event):# 新建事件
295 | cache.set(send_cache_key,1,expire=86400) # 发送标记缓存一天
296 |
297 | # 黑名单检查
298 | if is_msg_block(receiver=receiver,msg=message.text,channel_name=event_chat_username,channel_id=event.chat_id):
299 | continue
300 |
301 | await bot.send_message(receiver, message_str,link_preview = True,parse_mode = 'markdown')
302 | else:
303 | # 已发送该消息
304 | logger.debug(f'REGEX send repeat. rule_name:{config["msg_unique_rule"]} {CACHE_KEY_UNIQUE_SEND}:{channel_msg_url}')
305 | continue
306 |
307 | else:
308 | logger.debug(f'regex_match empty. regex:{keywords} ,message: t.me/{event_chat_username}/{event.message.id}')
309 | else:#普通模式
310 | if keywords in text:
311 | # # {chat_title} \n\n
312 | channel_title = f"\n\nCHANNEL: {chat_title}" if not event_chat_username else ""
313 | message_str = f'[#FOUND]({channel_msg_url}) **{keywords}**{channel_title}'
314 | if cache.add(CACHE_KEY_UNIQUE_SEND,1,expire=5):
315 | logger.info(f'TEXT: receiver chat_id:{receiver}, l_id:{l_id}, message_str:{message_str}')
316 | if isinstance(event,events.NewMessage.Event):# 新建事件
317 | cache.set(send_cache_key,1,expire=86400) # 发送标记缓存一天
318 |
319 | # 黑名单检查
320 | if is_msg_block(receiver=receiver,msg=message.text,channel_name=event_chat_username,channel_id=event.chat_id):
321 | continue
322 |
323 | await bot.send_message(receiver, message_str,link_preview = True,parse_mode = 'markdown')
324 | else:
325 | # 已发送该消息
326 | logger.debug(f'TEXT send repeat. rule_name:{config["msg_unique_rule"]} {CACHE_KEY_UNIQUE_SEND}:{channel_msg_url}')
327 | continue
328 | except errors.rpcerrorlist.UserIsBlockedError as _e:
329 | # User is blocked (caused by SendMessageRequest) 用户已手动停止bot
330 | logger.error(f'{_e}')
331 | pass # 关闭全部订阅
332 | except ValueError as _e:
333 | # 用户从未使用bot
334 | logger.error(f'{_e}')
335 | # 删除用户订阅和id
336 | isdel = utils.db.user.delete().where(utils.User.chat_id == receiver).execute()
337 | user_id = utils.db.user.get_or_none(chat_id=receiver)
338 | if user_id:
339 | isdel2 = utils.db.user_subscribe_list.delete().where(utils.User_subscribe_list.user_id == user_id.id).execute()
340 | except AssertionError as _e:
341 | raise _e
342 | except Exception as _e:
343 | logger.error(f'{_e}')
344 | else:
345 | logger.debug(f'sql find empty. event.chat.username:{event_chat_username}, find:{find}, sql:{sql}')
346 |
347 | if 'auto_leave_channel' in config and config['auto_leave_channel']:
348 | if event_chat_username:# 公开频道/组
349 | logger.info(f'Leave Channel/group: {event_chat_username}')
350 | await leave_channel(event_chat_username)
351 |
352 |
353 | # bot相关操作
354 | def parse_url(url):
355 | """
356 | 解析url信息
357 | 根据urllib.parse操作 避免它将分号设置为参数的分割符以出现params的问题
358 | Args:
359 | url ([type]): [string]
360 |
361 | Returns:
362 | [dict]: [按照个人认为的字段区域名称] :///?#
363 | """
364 | if regex.search(r'^t\.me/',url):
365 | url = f'http://{url}'
366 |
367 | res = urlparse(url) # :///;?#
368 | result = {}
369 | result['scheme'],result['host'],result['uri'],result['_params'],result['query'],result['fragment'] = list(res)
370 | if result['_params'] or ';?' in url:
371 | result['uri'] += ';'+result['_params']
372 | del result['_params']
373 | return result
374 |
375 | def get_channel_url(event_chat_username,event_chat__id):
376 | """
377 | 获取频道/群组 url
378 | 优先返回chat_id的url
379 |
380 | https://docs.telethon.dev/en/latest/concepts/chats-vs-channels.html#converting-ids
381 |
382 | Args:
383 | event_chat_username (str): 频道名地址 e.g. tianfutong
384 | event_chat__id (str): 频道的非官方id。 e.g. -1001630956637
385 | """
386 | # event.is_private 无法判断
387 | # 判断私有频道
388 | # is_private = True if not event_chat_username else False
389 | host = 'https://t.me/'
390 | url = ''
391 | if event_chat__id:
392 | real_id, peer_type = telethon_utils.resolve_id(int(event_chat__id)) # 转换为官方真实id
393 | url = f'{host}c/{real_id}/'
394 | elif event_chat_username:
395 | url = f'{host}{event_chat_username}/'
396 | return url
397 |
398 |
399 | def parse_full_command(command, keywords, channels):
400 | """
401 | 处理多字段的命令参数 拼接合并返回
402 | Args:
403 | command ([type]): [命令 如 subscribe unsubscribe]
404 | keywords ([type]): [description]
405 | channels ([type]): [description]
406 |
407 | Returns:
408 | [type]: [description]
409 | """
410 | keywords_list = keywords.split(',')
411 | if is_regex_str(keywords):# 正则字符串
412 | keywords_list = [keywords]
413 |
414 | channels_list = channels.split(',')
415 | res = {}
416 | for keyword in keywords_list:
417 | keyword = keyword.strip()
418 | for channel in channels_list:
419 | channel = channel.strip()
420 | uri = parse_url(channel)['uri']
421 | channel = uri.strip('/')
422 | channel = regex.sub('^joinchat/(.+)',r'+\1',channel)
423 | find_channel = regex.search(r'^c/(\d+)|^(\+.+)',channel)
424 | if find_channel:
425 | for i in find_channel.groups():
426 | if i:
427 | channel = i
428 | break
429 | res[f'{channel}{keyword}'] = (keyword,channel)# 去重
430 | return list(res.values())
431 |
432 | async def join_channel_insert_subscribe(user_id,keyword_channel_list):
433 | """
434 | 加入频道 且 写入订阅数据表
435 |
436 | 支持传入频道id
437 |
438 | Raises:
439 | events.StopPropagation: [description]
440 | """
441 | res = []
442 | # 加入频道
443 | for k,c in keyword_channel_list:
444 | username = ''
445 | chat_id = ''
446 | try:
447 | is_chat_invite_link = False
448 | if c.lstrip('-').isdigit():# 整数
449 | real_id, peer_type = telethon_utils.resolve_id(int(c))
450 | channel_entity = None
451 | # 不请求channel_entity
452 | # channel_entity = await client_get_entity(real_id, time.time() // 86400 )
453 | chat_id = telethon_utils.get_peer_id(PeerChannel(real_id)) # 转换为marked_id
454 | else:# 传入普通名称
455 | if regex.search(r'^\+',c):# 邀请链接
456 | is_chat_invite_link = True
457 | c = c.lstrip('+')
458 | channel_entity = None
459 | chat_id = ''
460 | chatinvite = await resolve_invit_hash(c)
461 | if chatinvite:
462 | chat_id,chat_title,channel_entity = chatinvite
463 | else:
464 | channel_entity = await client_get_entity(c, time.time() // 86400)
465 | chat_id = telethon_utils.get_peer_id(PeerChannel(channel_entity.id)) # 转换为marked_id
466 |
467 | if channel_entity:
468 | username = get_event_chat_username(channel_entity) or ''
469 |
470 | if channel_entity and not channel_entity.left: # 已加入该频道
471 | logger.warning(f'user_id:{user_id}触发检查 已加入该私有频道:{chat_id} invite_hash:{c}')
472 | res.append((k,username,chat_id))
473 | else:
474 | if is_chat_invite_link:
475 | # 通过邀请链接加入私有频道
476 | logger.info(f'user_id:{user_id}通过邀请链接加入私有频道{c}')
477 | await client(ImportChatInviteRequest(c))
478 | chatinvite = await resolve_invit_hash(c)
479 | if chatinvite:
480 | chat_id,chat_title,channel_entity = chatinvite
481 | res.append((k,username,chat_id))
482 | else:
483 | await client(JoinChannelRequest(channel_entity or chat_id))
484 | res.append((k,username,chat_id))
485 |
486 | except errors.InviteHashExpiredError as _e:
487 | logger.error(f'{c} InviteHashExpiredError ERROR:{_e}')
488 | return f'无法使用该频道邀请链接:{c}\nLink has expired.'
489 | except errors.UserAlreadyParticipantError as _e:# 重复加入私有频道
490 | logger.warning(f'{c} UserAlreadyParticipantError ERROR:{_e}')
491 | return f'无法使用该频道邀请链接:UserAlreadyParticipantError'
492 | except Exception as _e: # 不存在的频道
493 | logger.error(f'{c} JoinChannelRequest ERROR:{_e}')
494 |
495 | # 查询本地记录是否存在
496 | channel_name_or_chat_id = regex.sub(r'^(?:http[s]?://)?t.me/(?:c/)?','',c) # 清洗多余信息
497 | find = utils.db.connect.execute_sql('select 1 from user_subscribe_list where status = 0 and (channel_name = ? or chat_id = ?)' ,(channel_name_or_chat_id,channel_name_or_chat_id)).fetchall()
498 | logger.warning(f'{c} JoinChannelRequest fail. cache join. cache find count: {len(find)}')
499 | if find:
500 | if len(find) > 1: # 存在1条以上的记录 则直接返回加入成功
501 | if channel_name_or_chat_id.lstrip('-').isdigit():# 整数
502 | res.append((k,'',channel_name_or_chat_id))
503 | else:
504 | res.append((k,channel_name_or_chat_id,''))
505 | else:
506 | return '无法使用该频道:{}\n\nChannel error, unable to use: {}'.format(c,_e)
507 | else:
508 | return '无法使用该频道:{}\n\nChannel error, unable to use: {}'.format(c,_e)
509 |
510 | # 写入数据表
511 | result = []
512 | for keyword,channel_name,_chat_id in res:
513 | if not channel_name: channel_name = ''
514 |
515 | find = utils.db.user_subscribe_list.get_or_none(**{
516 | 'user_id':user_id,
517 | 'keywords':keyword,
518 | 'channel_name':channel_name,
519 | 'chat_id':_chat_id,
520 | })
521 |
522 | if find:
523 | re_update = utils.db.user_subscribe_list.update(status = 0 ).where(utils.User_subscribe_list.id == find.id)#更新状态
524 | re_update = re_update.execute()# 更新成功返回1,不管是否重复执行
525 | if re_update:
526 | result.append((find.id,keyword,channel_name,_chat_id))
527 | else:
528 | insert_res = utils.db.user_subscribe_list.create(**{
529 | 'user_id':user_id,
530 | 'keywords':keyword,
531 | 'channel_name':channel_name.replace('@',''),
532 | 'create_time':datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
533 | 'chat_id':_chat_id
534 | })
535 | if insert_res:
536 | result.append((insert_res.id,keyword,channel_name,_chat_id))
537 | return result
538 |
539 | async def leave_channel(channel_name):
540 | '''
541 | 退出无用的频道/组
542 |
543 | Args:
544 | channel_name ([type]): [description]
545 | '''
546 | try:
547 | await client(LeaveChannelRequest(channel_name))
548 | await client(DeleteChannelRequest(channel_name))
549 | await client(DeleteHistoryRequest(channel_name))
550 | logger.info(f'退出 {channel_name}')
551 | except Exception as _e: # 不存在的频道
552 | return f'无法退出该频道:{channel_name}, {_e}'
553 |
554 |
555 | def update_subscribe(user_id,keyword_channel_list):
556 | """
557 | 更新订阅数据表(取消订阅操作)
558 | """
559 | # 修改数据表
560 | result = []
561 | for keyword,channel_name in keyword_channel_list:
562 | find = utils.db.user_subscribe_list.get_or_none(**{
563 | 'user_id':user_id,
564 | 'keywords':keyword,
565 | 'channel_name':channel_name,
566 | })
567 | if find:
568 | re_update = utils.db.user_subscribe_list.update(status = 1 ).where(utils.User_subscribe_list.id == find)#更新状态
569 | re_update = re_update.execute()# 更新成功返回1,不管是否重复执行
570 | if re_update:
571 | result.append((keyword,channel_name))
572 | else:
573 | result.append((keyword,channel_name))
574 | return result
575 |
576 | @bot.on(events.NewMessage(pattern='/start'))
577 | async def start(event):
578 | """Send a message when the command /start is issued."""
579 | # insert chat_id
580 | chat_id = event.message.chat.id
581 |
582 | if chat_id:
583 | await event.respond(f'Your Telegram Chat ID is: `{chat_id}`')
584 |
585 | # 访问授权检查
586 | if not is_allow_access(chat_id):
587 | await event.respond('Opps! I\'m a private bot. 对不起, 这是一个私人专用的Bot')
588 | raise events.StopPropagation
589 |
590 | find = utils.db.user.get_or_none(chat_id=chat_id)
591 | if not find:
592 | insert_res = utils.db.user.create(**{
593 | 'chat_id':chat_id,
594 | 'create_time':datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
595 | })
596 | else: # 存在chat_id
597 | insert_res = True
598 |
599 | if insert_res:
600 | await event.respond('Hi! Please input /help , access usage.')
601 | else:
602 | await event.respond('Opps! Please try again /start ')
603 |
604 | raise events.StopPropagation
605 |
606 | @bot.on(events.NewMessage(pattern='/subscribe'))
607 | async def subscribe(event):
608 | """Send a message when the command /subscribe is issued."""
609 | # insert chat_id
610 | chat_id = event.message.chat.id
611 | if not is_allow_access(chat_id):
612 | await event.respond('Opps! I\'m a private bot. 对不起, 这是一个私人专用的Bot')
613 | raise events.StopPropagation
614 |
615 | find = utils.db.user.get_or_none(chat_id=chat_id)
616 | user_id = find
617 | if not find:# 不存在用户信息
618 | await event.respond('Failed. Please input /start')
619 | raise events.StopPropagation
620 |
621 | text = event.message.text
622 | text = text.replace(',',',')# 替换掉中文逗号
623 | text = regex.sub(r'\s*,\s*',',',text) # 确保英文逗号间隔中间都没有空格 如 "https://t.me/xiaobaiup, https://t.me/com9ji"
624 | splitd = [i for i in regex.split(r'\s+',text) if i]# 删除空元素
625 | if len(splitd) <= 1:
626 | msg = "输入需要订阅的关键字,支持js正则语法:\n`/[\s\S]*/ig`\n\nInput the keyword that needs to subscribe, support JS regular syntax:\n`/[\s\S]*/ig`"
627 | _text, entities = markdown.parse(msg)
628 | await event.respond(_text,formatting_entities=entities)
629 | cache.set('status_{}'.format(chat_id),{'current_status':'/subscribe keywords','record_value':text},expire=5*60)#设置5m后过期
630 | elif len(splitd) == 3:
631 | command, keywords, channels = splitd
632 | result = await join_channel_insert_subscribe(user_id,parse_full_command(command, keywords, channels))
633 | if isinstance(result,str):
634 | logger.error('join_channel_insert_subscribe 错误:'+result)
635 | await event.respond(result,parse_mode = None) # 提示错误消息
636 | else:
637 | msg = ''
638 | for subscribeid,key,channel,_chat_id in result:
639 | if _chat_id:
640 | _chat_id, peer_type = telethon_utils.resolve_id(int(_chat_id))
641 |
642 | if not channel:
643 | channel = f'{_chat_id}'
644 | msg += build_sublist_msg(subscribeid,'Keywords',key,channel)
645 |
646 | if msg:
647 | msg = 'success subscribe:\n\n'+msg
648 | text, entities = html.parse(msg)# 解析超大文本 分批次发送 避免输出报错
649 | for text, entities in telethon_utils.split_text(text, entities):
650 | await event.respond(text,formatting_entities=entities)
651 | #await event.respond('success subscribe:\n'+msg,parse_mode = None)
652 | raise events.StopPropagation
653 |
654 |
655 | @bot.on(events.NewMessage(pattern='/unsubscribe_all'))
656 | async def unsubscribe_all(event):
657 | """Send a message when the command /unsubscribe_all is issued."""
658 | # insert chat_id
659 | chat_id = event.message.chat.id
660 | find = utils.db.user.get_or_none(chat_id=chat_id)
661 | if not find:# 不存在用户信息
662 | await event.respond('Failed. Please input /start')
663 | raise events.StopPropagation
664 | user_id = find.id
665 |
666 | # 查找当前的订阅数据
667 | _user_subscribe_list = utils.db.connect.execute_sql('select keywords,channel_name,chat_id from user_subscribe_list where user_id = %d and status = %d' % (user_id,0) ).fetchall()
668 | if _user_subscribe_list:
669 | msg = ''
670 | for keywords,channel_name,chat_id in _user_subscribe_list:
671 | channel_url = get_channel_url(channel_name,chat_id)
672 | msg += f'Keyword: {keywords}\nChannel: {channel_url}\n{"---"*12}\n'
673 |
674 |
675 | re_update = utils.db.user_subscribe_list.update(status = 1 ).where(utils.User_subscribe_list.user_id == user_id)#更新状态
676 | re_update = re_update.execute()# 更新成功返回1,不管是否重复执行
677 | if re_update:
678 | # await event.respond('success unsubscribe_all:\n' + msg,link_preview = False,parse_mode = None)
679 | text, entities = html.parse('success unsubscribe_all:\n' + msg)# 解析超大文本 分批次发送 避免输出报错
680 | for text, entities in telethon_utils.split_text(text, entities):
681 | await event.respond(text,formatting_entities=entities)
682 |
683 | else:
684 | await event.respond('not found unsubscribe list')
685 | raise events.StopPropagation
686 |
687 |
688 | @bot.on(events.NewMessage(pattern='/unsubscribe_id'))
689 | async def unsubscribe_id(event):
690 | '''
691 | 根据id取消订阅
692 | '''
693 | chat_id = event.message.chat.id
694 | find = utils.db.user.get_or_none(chat_id=chat_id)
695 | user_id = find
696 | if not find:# 不存在用户信息
697 | await event.respond('Failed. Please input /start')
698 | raise events.StopPropagation
699 | text = event.message.text
700 | text = text.replace(',',',')# 替换掉中文逗号
701 | text = regex.sub(r'\s*,\s*',',',text) # 确保英文逗号间隔中间都没有空格 如 "https://t.me/xiaobaiup, https://t.me/com9ji"
702 | splitd = [i for i in regex.split(r'\s+',text) if i]# 删除空元素
703 | if len(splitd) > 1:
704 | ids = [int(i) for i in splitd[1].split(',') if i.isnumeric()]
705 | if not ids:
706 | await event.respond('Please input your unsubscribe_id. \ne.g. `/unsubscribe_id 123,321`')
707 | raise events.StopPropagation
708 | result = []
709 | for i in ids:
710 | re_update = utils.db.user_subscribe_list.update(status = 1 ).where(utils.User_subscribe_list.id == i,utils.User_subscribe_list.user_id == user_id)#更新状态
711 | re_update = re_update.execute()# 更新成功返回1,不管是否重复执行
712 | if re_update:
713 | result.append(i)
714 | await event.respond('success unsubscribe id:{}'.format(result if result else 'None'))
715 | elif len(splitd) < 2:
716 | await event.respond('输入需要**取消订阅**的订阅id:\n\nEnter the subscription id of the channel where ** unsubscribe **is required:')
717 | cache.set('status_{}'.format(chat_id),{'current_status':'/unsubscribe_id ids','record_value':None},expire=5*60)# 记录输入的关键字
718 | raise events.StopPropagation
719 | else:
720 | await event.respond('not found id')
721 | raise events.StopPropagation
722 |
723 |
724 | @bot.on(events.NewMessage(pattern='/unsubscribe'))
725 | async def unsubscribe(event):
726 | """Send a message when the command /unsubscribe is issued."""
727 | # insert chat_id
728 | chat_id = event.message.chat.id
729 | find = utils.db.user.get_or_none(chat_id=chat_id)
730 | user_id = find
731 | if not find:# 不存在用户信息
732 | await event.respond('Failed. Please input /start')
733 | raise events.StopPropagation
734 |
735 |
736 | text = event.message.text
737 | text = text.replace(',',',')# 替换掉中文逗号
738 | text = regex.sub(r'\s*,\s*',',',text) # 确保英文逗号间隔中间都没有空格 如 "https://t.me/xiaobaiup, https://t.me/com9ji"
739 | splitd = [i for i in regex.split(r'\s+',text) if i]# 删除空元素
740 | if len(splitd) <= 1:
741 | await event.respond('输入需要**取消订阅**的关键字\n\nEnter a keyword that requires **unsubscribe**')
742 | cache.set('status_{}'.format(chat_id),{'current_status':'/unsubscribe keywords','record_value':text},expire=5*60)#设置5m后过期
743 | elif len(splitd) == 3:
744 | command, keywords, channels = splitd
745 | result = update_subscribe(user_id,parse_full_command(command, keywords, channels))
746 | # msg = ''
747 | # for key,channel in result:
748 | # msg += 'keyword:{} channel:{}\n'.format(key,channel)
749 | # if msg:
750 | # await event.respond('success unsubscribe:\n'+msg,parse_mode = None)
751 | await event.respond('success unsubscribe.')
752 |
753 | raise events.StopPropagation
754 |
755 |
756 | # 限制消息文本长度
757 | @bot.on(events.NewMessage(pattern='/setlengthlimit'))
758 | async def setlengthlimit(event):
759 | blacklist_type = 'length_limit'
760 | command = r'/setlengthlimit'
761 | # get chat_id
762 | chat_id = event.message.chat.id
763 | find = utils.db.user.get_or_none(chat_id=chat_id)
764 | user_id = find
765 | if not find: # 用户信息不存在
766 | await event.respond('Failed. Please input /start')
767 | raise events.StopPropagation
768 |
769 | # parse input
770 | text = event.message.text
771 | text = text.replace(',', ',') # 替换掉中文逗号
772 | text = regex.sub(f'^{command}', '', text).strip() # 确保英文逗号间隔中间都没有空格
773 | splitd = [i for i in text.split(',') if i] # 删除空元素
774 |
775 | find = utils.db.connect.execute_sql('select id,blacklist_value from user_block_list where user_id = ? and blacklist_type=? ' ,(user_id.id,blacklist_type)).fetchone()
776 | if not splitd:
777 | if find is None:
778 | await event.respond(f'lengthlimit not found.')
779 | else:
780 | await event.respond(f'setlengthlimit `{find[1]}`')
781 | else: # 传入多参数 e.g. /setlengthlimit 123
782 | if len(splitd) == 1 and splitd[0].isdigit():
783 | blacklist_value = int(splitd[0])
784 |
785 | if find is None:
786 | # create entry in UserBlockList
787 | insert_res = utils.db.user_block_list.create(**{
788 | 'user_id': user_id,
789 | 'channel_name': '',
790 | 'chat_id': '',
791 | 'blacklist_type': blacklist_type,
792 | 'blacklist_value': blacklist_value,
793 | 'create_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
794 | 'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
795 | })
796 |
797 | if insert_res:
798 | await event.respond(f'Success lengthlimit `{blacklist_value}`')
799 | else:
800 | await event.respond(f'Failed lengthlimit `{blacklist_value}`')
801 | else:
802 | update_query = utils.db.user_block_list.update(blacklist_value = blacklist_value,update_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')).where(utils.User_block_list.id == find[0])#更新状态
803 | update_result = update_query.execute()# 更新成功返回1,不管是否重复执行
804 | if update_result:
805 | await event.respond(f'Success lengthlimit `{blacklist_value}`')
806 | else:
807 | await event.respond(f'Failed lengthlimit `{blacklist_value}`')
808 | raise events.StopPropagation
809 |
810 |
811 | @bot.on(events.NewMessage(pattern='/help'))
812 | async def start(event):
813 | await event.respond('''
814 |
815 | 目的:根据关键字订阅频道消息,支持群组
816 |
817 | BUG反馈:https://git.io/JJ0Ey
818 |
819 | 支持多关键字和多频道订阅,使用英文逗号`,`间隔
820 |
821 | 关键字和频道之间使用空格间隔
822 |
823 | 主要命令:
824 |
825 | - 订阅操作
826 |
827 | /subscribe 关键字1,关键字2 tianfutong,xiaobaiup
828 |
829 | /subscribe 关键字1,关键字2 https://t.me/tianfutong,https://t.me/xiaobaiup
830 |
831 | - 取消订阅
832 |
833 | /unsubscribe 关键字1,关键字2 https://t.me/tianfutong,https://t.me/xiaobaiup
834 |
835 | - 取消订阅id
836 |
837 | /unsubscribe_id 1,2
838 |
839 | - 取消所有订阅
840 |
841 | /unsubscribe_all
842 |
843 | - 显示所有订阅列表
844 |
845 | /list
846 |
847 | ---
848 | Purpose: Subscribe to channel messages based on keywords. Support groups
849 |
850 | BUG FEEDBACK: https://git.io/JJ0Ey
851 |
852 | Multi-keyword and multi-channel subscription support, using comma `,` interval.
853 |
854 | Use space between keywords and channels
855 |
856 | Main command:
857 |
858 | /subscribe keyword1,keyword2 tianfutong,xiaobaiup
859 | /subscribe keyword1,keyword2 https://t.me/tianfutong,https://t.me/xiaobaiup
860 |
861 | /unsubscribe keyword1,keyword2 https://t.me/tianfutong,https://t.me/xiaobaiup
862 |
863 | /unsubscribe_id 1,2
864 |
865 | /unsubscribe_all
866 |
867 | /list
868 |
869 | ''')
870 | raise events.StopPropagation
871 |
872 |
873 | # 删除当前记录的用户状态
874 | @bot.on(events.NewMessage(pattern='/cancel'))
875 | async def cancel(event):
876 | chat_id = event.message.chat.id
877 | _ = cache.delete('status_{}'.format(chat_id))
878 | if _ :
879 | await event.respond('success cancel.')
880 | raise events.StopPropagation
881 |
882 | # 查询当前用户的所有订阅
883 | @bot.on(events.NewMessage(pattern='/list'))
884 | async def _list(event):
885 | chat_id = event.message.chat.id
886 | find = utils.db.user.get_or_none(**{
887 | 'chat_id':chat_id,
888 | })
889 | if find:
890 | find = utils.db.connect.execute_sql('select id,keywords,channel_name,chat_id from user_subscribe_list where user_id = %d and status = %d' % (find.id,0) ).fetchall()
891 | if find:
892 | msg = ''
893 | for sub_id,keywords,channel_name,chat_id in find:
894 | _type = 'regex' if is_regex_str_fuzzy(keywords) else 'keyword'
895 | channel_url = get_channel_url(channel_name,chat_id)
896 |
897 | channel_entity = None # TODO 不执行实体信息读取 否则会无响应
898 | # _entity = int(chat_id) if chat_id else channel_name
899 | # # channel_entity1 = await client.get_entity('tianfutong')
900 | # # channel_entity2 = await client.get_entity('@tianfutong')
901 | # # channel_entity3 = await client.get_entity(-1001242421091)
902 | # # channel_entity4 = await client.get_entity(1242421091)
903 | # try:
904 | # channel_entity = await client.get_entity(_entity)# 获取频道相关信息
905 | # except ValueError as _e:# 频道不存在报错
906 | # pass
907 | # # logger.info(f'delete user_subscribe_list channel id:{sub_id} _entity:{_entity}')
908 | # # re_update = utils.db.user_subscribe_list.update(status = 1 ).where(utils.User_subscribe_list.id == sub_id)
909 | # # re_update.execute()
910 | # class channel_entity: username='';title=''
911 |
912 | channel_title = ''
913 | if channel_entity and channel_entity.title:channel_title = f'channel title: {channel_entity.title}\n'
914 |
915 | if channel_name:
916 | if channel_entity:
917 | if channel_entity.username:
918 | if channel_entity.username != channel_name:
919 | channel_name += '\t[CHANNEL NAME EXPIRED]'# 标记频道名称过期
920 | # channel_name = '' # 不显示
921 | logger.info(f'channel username:{channel_name} expired.')
922 | else:
923 | channel_name += '\t[CHANNEL NONE EXPIRED]'# 标记频道名称过期.当前不存在
924 | # channel_name = '' # 不显示
925 | logger.info(f'channel username:{channel_name} expired. current none')
926 | elif chat_id:# 只有chat_id
927 | if channel_entity and channel_entity.username:
928 | channel_name = channel_entity.username
929 | logger.info(f'channel chat_id:{chat_id} username:{channel_name}')
930 |
931 | channel_username = ''
932 | if channel_entity:# 有实体信息才显示频道名
933 | if channel_name:
934 | channel_username = f'channel username: {channel_name}\n'
935 |
936 | channel_url = f'{"https://t.me/"+channel_name if channel_name else channel_url}'
937 | msg += build_sublist_msg(sub_id,_type,keywords,channel_url,channel_title,channel_username)
938 |
939 | text, entities = html.parse(msg)# 解析超大文本 分批次发送 避免输出报错
940 | for text, entities in telethon_utils.split_text(text, entities):
941 | # await client.send_message(chat, text, formatting_entities=entities)
942 | await event.respond(text,formatting_entities=entities)
943 | else:
944 | await event.respond('not found list')
945 | else:
946 | await event.respond('please /start')
947 | raise events.StopPropagation
948 |
949 |
950 | # 其余消息的统一处理方法
951 | @bot.on(events.NewMessage)
952 | async def common(event):
953 | """Echo the user message."""
954 | chat_id = event.message.chat.id
955 | text = event.text
956 | text = text.replace(',',',')# 替换掉中文逗号
957 | text = regex.sub(r'\s*,\s*',',',text) # 确保英文逗号间隔中间都没有空格 如 "https://t.me/xiaobaiup, https://t.me/com9ji"
958 |
959 | find = cache.get('status_{}'.format(chat_id))
960 | if find:
961 |
962 | # 执行订阅
963 | if find['current_status'] == '/subscribe keywords':# 当前输入关键字
964 | await event.respond('输入需要订阅的频道url或者name:\n\nEnter the url or name of the channel to subscribe to:')
965 | cache.set('status_{}'.format(chat_id),{'current_status':'/subscribe channels','record_value':find['record_value'] + ' ' + text},expire=5*60)# 记录输入的关键字
966 | raise events.StopPropagation
967 | elif find['current_status'] == '/subscribe channels':# 当前输入频道
968 | full_command = find['record_value'] + ' ' + text
969 | splitd = [i for i in regex.split(r'\s+',full_command) if i]# 删除空元素
970 | if len(splitd) != 3:
971 | await event.respond('关键字请不要包含空格 可使用正则表达式解决\n\nThe keyword must not contain Spaces.')
972 | raise events.StopPropagation
973 | command, keywords, channels = splitd
974 | user_id = utils.db.user.get_or_none(chat_id=chat_id)
975 | result = await join_channel_insert_subscribe(user_id,parse_full_command(command, keywords, channels))
976 | if isinstance(result,str):
977 | await event.respond(result,parse_mode = None) # 提示错误消息
978 | else:
979 | msg = ''
980 | for subscribeid,key,channel,_chat_id in result:
981 | if _chat_id:
982 | _chat_id, peer_type = telethon_utils.resolve_id(int(_chat_id))
983 |
984 | if not channel:
985 | channel = f'{_chat_id}'
986 | msg += build_sublist_msg(subscribeid,'Keywords',key,channel)
987 |
988 | if msg:
989 | # await event.respond('success subscribe:\n'+msg,parse_mode = None)
990 | msg = 'success subscribe:\n\n'+msg
991 | text, entities = html.parse(msg)# 解析超大文本 分批次发送 避免输出报错
992 | for text, entities in telethon_utils.split_text(text, entities):
993 | await event.respond(text,formatting_entities=entities)
994 |
995 | cache.delete('status_{}'.format(chat_id))
996 | raise events.StopPropagation
997 |
998 | #取消订阅
999 | elif find['current_status'] == '/unsubscribe keywords':# 当前输入关键字
1000 | await event.respond('输入需要**取消订阅**的频道url或者name:\n\nEnter the url or name of the channel where ** unsubscribe **is required:')
1001 | cache.set('status_{}'.format(chat_id),{'current_status':'/unsubscribe channels','record_value':find['record_value'] + ' ' + text},expire=5*60)# 记录输入的关键字
1002 | raise events.StopPropagation
1003 | elif find['current_status'] == '/unsubscribe channels':# 当前输入频道
1004 | full_command = find['record_value'] + ' ' + text
1005 | splitd = [i for i in regex.split(r'\s+',full_command) if i]# 删除空元素
1006 | if len(splitd) != 3:
1007 | await event.respond('关键字请不要包含空格 可使用正则表达式解决\n\nThe keyword must not contain Spaces.')
1008 | raise events.StopPropagation
1009 | command, keywords, channels = splitd
1010 | user_id = utils.db.user.get_or_none(chat_id=chat_id)
1011 | result = update_subscribe(user_id,parse_full_command(command, keywords, channels))
1012 | # msg = ''
1013 | # for key,channel in result:
1014 | # msg += '{},{}\n'.format(key,channel)
1015 | # if msg:
1016 | # await event.respond('success:\n'+msg,parse_mode = None)
1017 | await event.respond('success unsubscribe..')
1018 |
1019 | cache.delete('status_{}'.format(chat_id))
1020 | raise events.StopPropagation
1021 | elif find['current_status'] == '/unsubscribe_id ids':# 当前输入订阅id
1022 | splitd = text.strip().split(',')
1023 | user_id = utils.db.user.get_or_none(chat_id=chat_id)
1024 | result = []
1025 | for i in splitd:
1026 | if not i.isdigit():
1027 | continue
1028 | i = int(i)
1029 | re_update = utils.db.user_subscribe_list.update(status = 1 ).where(utils.User_subscribe_list.id == i,utils.User_subscribe_list.user_id == user_id)#更新状态
1030 | re_update = re_update.execute()# 更新成功返回1,不管是否重复执行
1031 | if re_update:
1032 | result.append(i)
1033 | await event.respond('success unsubscribe id:{}'.format(result if result else 'None'))
1034 | raise events.StopPropagation
1035 |
1036 | if __name__ == "__main__":
1037 | cache.expire()
1038 | print(banner())
1039 | # 开启client loop。防止进程退出
1040 | client.run_until_disconnected()
1041 |
--------------------------------------------------------------------------------