当前位置: 首页 > news >正文

【python实用小脚本-43】用Python自动发送生日祝福,让情感更高效

一、应用场景故事

每年生日,我们总是忙于工作,忘记给朋友和家人送上祝福。手工发送祝福信息不仅耗时,还容易遗漏重要的人。要是能用代码实现自动化祝福,那该多好!于是,我写了一个Python脚本,利用Telegram API在特定日期自动发送生日祝福。这不仅节省了时间,还让祝福变得更有心意。

二、核心代码解析

1. datetime.date.today()
today = datetime.date.today()

技术原理
这行代码的作用是获取当前日期。datetime模块是Python内置的用于处理日期和时间的工具,就像一个“时间机器”,可以轻松获取和操作日期信息。

参数作用
today()方法会返回当前日期,格式为年-月-日。就像一个日历,直接告诉你“今天是哪一天”。

易错点提示
新手可能会混淆datetime.datedatetime.datetime,前者只包含日期,后者包含日期和时间。如果只需要日期,就用datetime.date

复杂度分析
时间复杂度:O(1),获取当前日期是一个常数时间操作。
空间复杂度:O(1),不占用额外空间。

学以致用练习题
如何修改代码,让它在每个月的第一天提醒你检查账单?

2. TelegramClient
client = TelegramClient('session', api_id, api_hash)

技术原理
TelegramClienttelethon库的核心工具,用于连接Telegram API。它就像一个“信使”,负责将消息发送到指定的用户或群组。

参数作用

  • 'session':会话文件名,用于保存登录状态。
  • api_idapi_hash:Telegram API的认证信息,相当于“通行证”。
  • phone:绑定的手机号码,用于登录验证。

易错点提示
新手可能会忘记填写api_idapi_hash,或者填错手机号码,导致无法登录。这些信息需要在Telegram的开发者平台申请。

复杂度分析
时间复杂度:O(1),连接操作是常数时间复杂度。
空间复杂度:O(1),不占用额外空间。

学以致用练习题
如何修改代码,让它支持发送图片或语音消息?

3. client.send_message()
client.send_message(receiver, msg, parse_mode='html')

技术原理
这行代码的作用是发送消息。send_message方法通过Telegram API将消息发送到指定用户或群组。它就像一个“快递员”,负责把消息送到目的地。

参数作用

  • receiver:接收者的用户ID或群组ID。
  • msg:要发送的消息内容。
  • parse_mode:消息格式,支持htmlmarkdown,可以让消息更美观。

易错点提示
新手可能会忘记设置parse_mode,导致消息格式混乱。另外,receiver必须是有效的用户ID或群组ID,否则消息无法送达。

复杂度分析
时间复杂度:O(1),发送消息是一个常数时间操作。
空间复杂度:O(1),不占用额外空间。

学以致用练习题
如何修改代码,让它支持群发消息给多个用户?

三、扩展应用场景开发

基础版:定时发送生日祝福

场景痛点
手动发送生日祝福容易忘记,而且耗时。

技术选型对比

  • 手动发送:效率低,容易遗漏。
  • 定时脚本:使用datetimetelethon,自动化发送祝福。

代码改进示范

import datetime
from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerUserapi_id = '<API ID>'
api_hash = '<API HASH>'
phone = '<手机号>'def send_message(msg, user_id, user_hash):client = TelegramClient('session', api_id, api_hash)client.connect()if not client.is_user_authorized():client.send_code_request(phone)client.sign_in(phone, input('Enter the code: '))try:receiver = InputPeerUser(user_id, user_hash)client.send_message(receiver, msg, parse_mode='html')except Exception as e:print(e)client.disconnect()if __name__ == "__main__":today = datetime.date.today()if today == datetime.date(2024, 10, 15):  # 修改为实际生日日期send_message("Happy Birthday!", 'user_id', 'user_hash')
专业版:批量发送祝福

场景痛点
需要给多个朋友发送生日祝福,手动操作效率低下。

技术选型对比

  • 单个发送:逐个发送,效率低。
  • 批量发送:使用列表存储用户ID,循环发送。

代码改进示范

import datetime
from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerUserapi_id = '<API ID>'
api_hash = '<API HASH>'
phone = '<手机号>'def send_message(msg, user_id, user_hash):client = TelegramClient('session', api_id, api_hash)client.connect()if not client.is_user_authorized():client.send_code_request(phone)client.sign_in(phone, input('Enter the code: '))try:receiver = InputPeerUser(user_id, user_hash)client.send_message(receiver, msg, parse_mode='html')except Exception as e:print(e)client.disconnect()if __name__ == "__main__":today = datetime.date.today()if today == datetime.date(2024, 10, 15):  # 修改为实际生日日期friends = [{'user_id': 'friend1_id', 'user_hash': 'friend1_hash'},{'user_id': 'friend2_id', 'user_hash': 'friend2_hash'}]for friend in friends:send_message("Happy Birthday!", friend['user_id'], friend['user_hash'])

四、教学代码示例

案例1:办公自动化方向(自动发送会议提醒)

应用场景说明
在日常工作中,我们常常需要提醒同事参加重要的会议。手动发送提醒容易遗漏,而且效率低下。通过Python脚本,我们可以自动发送会议提醒,确保每个人都能按时参加会议。

代码骨架

import datetime
from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerUser# 替换为你的Telegram API信息
api_id = '你的API ID'
api_hash = '你的API HASH'
phone = '你的手机号'def send_message(msg, user_id, user_hash):client = TelegramClient('session', api_id, api_hash)client.connect()if not client.is_user_authorized():client.send_code_request(phone)client.sign_in(phone, input('请输入验证码:'))try:receiver = InputPeerUser(user_id, user_hash)client.send_message(receiver, msg, parse_mode='html')except Exception as e:print(f"发送消息失败:{e}")client.disconnect()if __name__ == "__main__":today = datetime.date.today()if today == datetime.date(2024, 10, 15):  # 修改为实际日期colleagues = [{'user_id': '同事1的ID', 'user_hash': '同事1的hash'},{'user_id': '同事2的ID', 'user_hash': '同事2的hash'}]for colleague in colleagues:send_message("会议提醒:今天下午3点,会议室1,重要会议,请准时参加!", colleague['user_id'], colleague['user_hash'])
案例2:生活自动化方向(自动发送节日祝福)

应用场景说明
在中国的传统节日中,如春节、中秋节等,给亲朋好友发送祝福信息是一种重要的社交礼仪。手动发送祝福信息不仅耗时,还容易遗漏重要的人。通过Python脚本,我们可以自动发送节日祝福,让情感传递更加高效。

代码骨架

import datetime
from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerUser# 替换为你的Telegram API信息
api_id = '你的API ID'
api_hash = '你的API HASH'
phone = '你的手机号'def send_message(msg, user_id, user_hash):client = TelegramClient('session', api_id, api_hash)client.connect()if not client.is_user_authorized():client.send_code_request(phone)client.sign_in(phone, input('请输入验证码:'))try:receiver = InputPeerUser(user_id, user_hash)client.send_message(receiver, msg, parse_mode='html')except Exception as e:print(f"发送消息失败:{e}")client.disconnect()if __name__ == "__main__":today = datetime.date.today()if today == datetime.date(2024, 10, 1):  # 修改为实际日期family_members = [{'user_id': '家人1的ID', 'user_hash': '家人1的hash'},{'user_id': '家人2的ID', 'user_hash': '家人2的hash'}]for member in family_members:send_message("国庆快乐!祝您和家人幸福安康!", member['user_id'], member['user_hash'])

五、总结

这个案例的完整源码已开源在我的GitCode仓库,可自行搜索下载,如果需要完整可运行的版本,老规矩——评论区留言“代码包”,我会第一时间私信发你。

http://www.xdnf.cn/news/239167.html

相关文章:

  • 架构进阶:72页集管IT基础设施蓝图设计方案【附全文阅读】
  • Nautilus侧栏没有桌面
  • 通过Yoast设置SEO标题不生效
  • OpenCV学习笔记(完)
  • Linux -- 操作系统
  • dubbo泛化调用时transient字段失效问题
  • 什么是基尔霍夫第一定律
  • 【python】-基础语法3
  • Semtech公司简介以及主流产品
  • C++继承(下)
  • 【补题】Codeforces Global Round 20 D. Cyclic Rotation
  • Ethan独立开发产品日报 | 2025-04-29
  • 小白学习java第15天(中):javaWeb
  • 高斯-牛顿法与列文伯格-马夸尔特法:非线性优化的理论推导与C++实现
  • Java @Transactional事物隔离级别和默认值详解
  • git did not exit cleanly (exit code 128) 已解决
  • 0基础FWT详解2(巩固)
  • Databend 产品月报(2025年4月)
  • 算法竞赛进阶指南.沙漠之王
  • 如何加速机器学习模型训练:深入探讨与实用技巧
  • Decode
  • PixONE 六维力传感器:赋能 OEM 机器人,12 自由度精准感知
  • PC端实现微信扫码登录
  • 【Android】Android签名解析
  • TEN:开启实时语音交互的下一代AI Agent引擎
  • 54.[前端开发-前端工程化]Day01-Node-Node安装-前端模块化
  • 多通道协调加载试验机
  • SpringBoot+Redis全局唯一ID生成器
  • Redis应用场景实战:穿透/雪崩/击穿解决方案与分布式锁深度剖析
  • 【数据链路层深度解析】从帧结构到协议实现