用 Python 畅玩 Line bot - 19:加入与移除好友

当加入一个 line bot 的时候,通常 bot 会传送一个欢迎讯息给使用者,而此设定除了可以透过 Line Official Account Manger内,聊天室相关的部份去做设定之外,也可以透过 Line API 触发 follow/join event,去作出更弹性的欢迎讯息。
而 follow event 跟 join event 的差别在于,前者是个人加入 bot 时候会触发,后者是 bot 加入一个群组时会触发,有一点要注意的是,如果一个群组内已经有一个 line bot,便无法加入第二个 Line bot,会看到他自动退出。

(图一,欢迎讯息设定介面)
http://img2.58codes.com/2024/20142564rVKFBKrn03.png

(图二、加入第二个 Line bot 到群组)
http://img2.58codes.com/2024/201425643xV2H0Hdcw.jpg

加入

FollowEvent

follow enevt 跟 message event 一样有 reply token,也就是说可以透过reply_message去进行传送欢迎讯息,而如果想要记录下该使用者的资料,可以从 source 从取得 userID,配合下章会说明的取得使用者资料,存入资料库中以便日后使用。

{"mode": "active","replyToken": "099c617dedde4a309ebd9e989b61317f","source":     {    "type": "user",    "userId": "Ub8c776653b3d290b3c3f9d1b9c852cb9"    },"timestamp": 1634882086789,"type": "follow"}

JoinEvent

跟 follow enevt 基本上一样,不过此处 source 内的会是 groupID,发送的讯息是会到该群组,且不能透过成员在群组中触发 event,去私下传送讯息给在该成员。

{"mode": "active","replyToken": "099c617dedde4a309ebd9e989b61317f","source":     {    "groupId": "Ccf4e0e2b490e66ea6fb456102ee7b7ec",    "type": "group"    },"timestamp": 1634882746613,"type": "join"}

离开

离开或封锁该 Line bot 时候就会触发的 event,而因为该 event 并没有 reply token,因此不能在被封锁的时候还传送讯息,而这部份的 event 可以结合 follow event 运用在会员资料上,例如当触发 follow event 时,就将该名使用者的资料加入资料库中,当触发 unfollow event 时,就将该名使用者的资料移除资料库。

UnfollowEvent

{"mode": "active","source":     {    "type": "user",    "userId": "Ub8c776653b3d290b3c3f9d1b9c852cb9"    },"timestamp": 1634882067569,"type": "unfollow"}

LeaveEvent

{"mode": "active","source":     {    "groupId": "Ccf4e0e2b490e66ea6fb456102ee7b7ec",    "type": "group"    },"timestamp": 1634882775084,"type": "leave"}

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章