Last active
August 7, 2024 13:27
-
-
Save uvexz/0183d649e92b65e4ca03e6d8c622c95d to your computer and use it in GitHub Desktop.
Mastodon Comment Lottery Program
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import random | |
| from mastodon import Mastodon | |
| # Mastodon API 设置 | |
| mastodon = Mastodon( | |
| access_token = 'YOUR_ACCESS_TOKEN', | |
| api_base_url = 'https://mastodon.social' | |
| ) | |
| def get_post_comments(post_id): | |
| """获取指定帖子的所有评论""" | |
| comments = mastodon.status_context(post_id)['descendants'] | |
| return comments | |
| def is_local_user(account): | |
| """检查用户是否为本站用户""" | |
| return '@' not in account['acct'] | |
| def get_eligible_users(comments): | |
| """获取符合条件的本站用户列表""" | |
| eligible_users = set() | |
| for comment in comments: | |
| if is_local_user(comment['account']): | |
| eligible_users.add(comment['account']['acct']) | |
| return list(eligible_users) | |
| def draw_winner(eligible_users, num_winners=1): | |
| """从符合条件的用户中随机抽取指定数量的获奖者""" | |
| if len(eligible_users) < num_winners: | |
| return eligible_users | |
| return random.sample(eligible_users, num_winners) | |
| def main(): | |
| post_id = input("请输入 Mastodon 帖子 ID: ") | |
| num_winners = int(input("请输入要抽取的获奖者数量: ")) | |
| comments = get_post_comments(post_id) | |
| eligible_users = get_eligible_users(comments) | |
| winners = draw_winner(eligible_users, num_winners) | |
| print(f"\n共有 {len(comments)} 条评论") | |
| print(f"符合条件的本站用户数量:{len(eligible_users)}") | |
| print(f"抽取的 {len(winners)} 名获奖者是:") | |
| for winner in winners: | |
| print(winner) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
这个程序使用 Mastodon.py 库来与 Mastodon API 进行交互。以下是程序的主要功能:
get_post_comments(post_id): 获取指定帖子的所有评论。draw_winner(comments, num_winners): 从评论中随机抽取指定数量的获奖者。main(): 主函数,处理用户输入并执行抽奖流程。使用这个程序之前,您需要:
安装 Mastodon.py 库:
pip3 install Mastodon.py获取 Mastodon API 的访问令牌,并将其替换到代码中的
'YOUR_ACCESS_TOKEN'。如果您使用的不是
mastodon.social实例,请更改api_base_url。运行程序后,它会提示您输入 Mastodon 帖子的 ID 和想要抽取的获奖者数量,然后随机选择并显示获奖者。
请注意,这个程序假设所有评论都有资格获奖。