feat: 重构发送方式,使用 sqlite 记录内容,发送后标记为已发送

This commit is contained in:
Ching 2024-10-13 19:36:15 +08:00
parent 0954918fe3
commit ad524a2864
2 changed files with 65 additions and 18 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
toots.db
.python-version

75
send.py
View File

@ -1,30 +1,75 @@
from mastodon import Mastodon from mastodon import Mastodon
from loguru import logger from loguru import logger
import random import random
from peewee import *
# 数据库配置
db = SqliteDatabase('toots.db')
# read all toots from file # 定义 Toot 模型
with open('toots.txt', 'r') as f: class Toot(Model):
toots = f.read().split('\n\n') content = TextField(unique=True)
sent = BooleanField(default=False)
class Meta:
database = db
# Mastodon 配置
access_token = 'your access token' access_token = 'your access token'
instance = 'https://mastodon.social' instance = 'https://mastodon.social'
mastodon_cli = Mastodon( mastodon_cli = Mastodon(
access_token=access_token, api_base_url=instance) access_token=access_token, api_base_url=instance)
#randomly choose a toot def create_table():
toot = random.choice(toots) with db:
db.create_tables([Toot])
logger.info("数据库表已创建")
# post toot def insert_toots():
with open('toots.txt', 'r', encoding='utf-8') as f:
content = f.read()
toots = content.split('\n\n')
with db.atomic():
for toot in toots:
if toot.strip():
Toot.get_or_create(content=toot.strip())
logger.info(f"已插入 {len(toots)} 条 toot")
def get_random_toot():
unsent_toots = Toot.select().where(Toot.sent == False)
if unsent_toots.count() == 0:
Toot.update(sent=False).execute()
unsent_toots = Toot.select().where(Toot.sent == False)
logger.info("所有 toot 已重置为未发送状态")
return random.choice(unsent_toots) if unsent_toots.exists() else None
def main():
create_table()
insert_toots()
random_toot = get_random_toot()
if random_toot:
logger.info("随机选择的 toot:")
logger.info(random_toot.content)
# 发送 toot
try: try:
mastodon_cli.toot(toot) mastodon_cli.toot(random_toot.content)
logger.info('Toot posted, %s' % toot) logger.success(f'Toot 已发送: {random_toot.content}')
# remove toot from file
with open('toots.txt', 'w') as f: # 标记 toot 为已发送
f.write('\n\n'.join(toots)) random_toot.sent = True
# record toot random_toot.save()
with open('toots_sent.txt', 'a') as f: logger.info("Toot 已标记为已发送")
f.write('\n\n' + toot)
except Exception as e: except Exception as e:
logger.error(e) logger.error(f"发送 toot 时出错: {e}")
else:
logger.warning("没有找到未发送的 toot请确保数据库中有数据。")
if __name__ == "__main__":
logger.add("cantonese.log") # 添加文件日志
main()