Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # coding: utf-8
- import os
- from datetime import datetime
- from pytz import timezone
- from flask import Flask, request, abort
- from flask_apscheduler import APScheduler
- from linebot import (
- LineBotApi, WebhookHandler
- )
- from linebot.exceptions import (
- InvalidSignatureError
- )
- from linebot.models import (
- MessageEvent, TextMessage, TextSendMessage, SourceUser
- )
- app = Flask(__name__)
- channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)
- channel_secret = os.getenv('LINE_CHANNEL_SECRET', None)
- line_bot_api = LineBotApi(channel_access_token)
- handler = WebhookHandler(channel_secret)
- @app.route("/callback", methods=['POST'])
- def callback():
- # get X-Line-Signature header value
- signature = request.headers['X-Line-Signature']
- # get request body as text
- body = request.get_data(as_text=True)
- app.logger.info("Request body: " + body)
- # handle webhook body
- try:
- handler.handle(body, signature)
- except InvalidSignatureError:
- abort(400)
- return 'OK'
- @handler.add(MessageEvent, message=TextMessage)
- def handle_message(event):
- if event.message.text.strip() in ['++', '"++"', "Add me"]:
- if isinstance(event.source, SourceUser):
- profile = line_bot_api.get_profile(event.source.user_id)
- if profile.user_id not in users:
- users.add(profile.user_id)
- # update users list, should use database
- with open('./users.txt', 'w', encoding='utf8') as ws:
- print('\n'.join(list(users)), file=ws)
- line_bot_api.reply_message(
- event.reply_token,
- TextSendMessage(text=join_template.format(name=profile.display_name)))
- else: # reply other messages
- line_bot_api.reply_message(
- event.reply_token,
- TextSendMessage(text="Shut up, I am just a PROTOTYPE."))
- def update_txt():
- # just update my resource, should use database
- with open('./videos.txt', 'w', encoding='utf8') as ws:
- print('\n'.join(urls), file=ws)
- # message to all
- def broadcast_video():
- if len(urls) > 0:
- url = urls.pop(0)
- url, title = url.split('\t')
- line_bot_api.multicast(list(users),
- TextSendMessage(text=broadcast_template.format(url=url, title=title)))
- update_txt()
- else:
- print("No URL anymore.")
- ### The following is the configure for my service
- # my time schedule
- TRIGGER_HOUR = 22
- # template
- join_template = "親愛的{name}您好,已經加你進入英文小組名單囉,歡迎購買阿波羅貓貼圖,喵喵喵。"
- broadcast_template = "讀英文囉!\n{title}\n{url}"
- # get start time
- now = datetime.now()
- start_time = datetime(now.year, now.month, now.day, TRIGGER_HOUR, 0, 0)
- if start_time < now: start_time = start_time.replace(day=now.day+1)
- ### Setup config for Linebot
- class Config(object):
- JOBS = [
- {
- 'id': 'broadcast',
- 'func': '__main__:broadcast_video',
- 'trigger': 'cron',
- 'hour': TRIGGER_HOUR,
- 'minute': 0,
- 'second': 0,
- 'start_date': start_time,
- 'timezone': timezone('Asia/Taipei')
- }
- ]
- app.config.from_object(Config())
- scheduler = APScheduler()
- scheduler.api_enabled = True
- scheduler.init_app(app)
- scheduler.start()
- ### get users set, should use database
- users = set()
- if os.path.isfile('./users.txt'):
- users = set(open('./users.txt', 'r', encoding='utf8').read().strip().split('\n'))
- ### get urls, should use database
- with open('./videos.txt', 'r', encoding='utf8') as fs:
- urls = fs.read().strip().split('\n')
- if __name__ == "__main__":
- app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement