【python实用小脚本-43】用Python自动发送生日祝福,让情感更高效
一、应用场景故事
每年生日,我们总是忙于工作,忘记给朋友和家人送上祝福。手工发送祝福信息不仅耗时,还容易遗漏重要的人。要是能用代码实现自动化祝福,那该多好!于是,我写了一个Python脚本,利用Telegram API在特定日期自动发送生日祝福。这不仅节省了时间,还让祝福变得更有心意。
二、核心代码解析
1. datetime.date.today()
today = datetime.date.today()
技术原理
这行代码的作用是获取当前日期。datetime
模块是Python内置的用于处理日期和时间的工具,就像一个“时间机器”,可以轻松获取和操作日期信息。
参数作用
today()
方法会返回当前日期,格式为年-月-日
。就像一个日历,直接告诉你“今天是哪一天”。
易错点提示
新手可能会混淆datetime.date
和datetime.datetime
,前者只包含日期,后者包含日期和时间。如果只需要日期,就用datetime.date
。
复杂度分析
时间复杂度:O(1),获取当前日期是一个常数时间操作。
空间复杂度:O(1),不占用额外空间。
学以致用练习题
如何修改代码,让它在每个月的第一天提醒你检查账单?
2. TelegramClient
client = TelegramClient('session', api_id, api_hash)
技术原理
TelegramClient
是telethon
库的核心工具,用于连接Telegram API。它就像一个“信使”,负责将消息发送到指定的用户或群组。
参数作用
'session'
:会话文件名,用于保存登录状态。api_id
和api_hash
:Telegram API的认证信息,相当于“通行证”。phone
:绑定的手机号码,用于登录验证。
易错点提示
新手可能会忘记填写api_id
和api_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
:消息格式,支持html
或markdown
,可以让消息更美观。
易错点提示
新手可能会忘记设置parse_mode
,导致消息格式混乱。另外,receiver
必须是有效的用户ID或群组ID,否则消息无法送达。
复杂度分析
时间复杂度:O(1),发送消息是一个常数时间操作。
空间复杂度:O(1),不占用额外空间。
学以致用练习题
如何修改代码,让它支持群发消息给多个用户?
三、扩展应用场景开发
基础版:定时发送生日祝福
场景痛点
手动发送生日祝福容易忘记,而且耗时。
技术选型对比
- 手动发送:效率低,容易遗漏。
- 定时脚本:使用
datetime
和telethon
,自动化发送祝福。
代码改进示范
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仓库,可自行搜索下载,如果需要完整可运行的版本,老规矩——评论区留言“代码包”,我会第一时间私信发你。