SHARE
TWEET

Untitled

a guest Jun 25th, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3.  
  4. import os
  5. from datetime import datetime
  6. from pytz import timezone
  7.  
  8. from flask import Flask, request, abort
  9. from flask_apscheduler import APScheduler
  10.  
  11. from linebot import (
  12.     LineBotApi, WebhookHandler
  13. )
  14. from linebot.exceptions import (
  15.     InvalidSignatureError
  16. )
  17. from linebot.models import (
  18.     MessageEvent, TextMessage, TextSendMessage, SourceUser
  19. )
  20.  
  21. app = Flask(__name__)
  22.  
  23. channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)
  24. channel_secret = os.getenv('LINE_CHANNEL_SECRET', None)
  25.  
  26. line_bot_api = LineBotApi(channel_access_token)
  27. handler = WebhookHandler(channel_secret)
  28.  
  29.  
  30. @app.route("/callback", methods=['POST'])
  31. def callback():
  32.     # get X-Line-Signature header value
  33.     signature = request.headers['X-Line-Signature']
  34.  
  35.     # get request body as text
  36.     body = request.get_data(as_text=True)
  37.     app.logger.info("Request body: " + body)
  38.  
  39.     # handle webhook body
  40.     try:
  41.         handler.handle(body, signature)
  42.     except InvalidSignatureError:
  43.         abort(400)
  44.  
  45.     return 'OK'
  46.  
  47.  
  48. @handler.add(MessageEvent, message=TextMessage)
  49. def handle_message(event):
  50.        
  51.     if event.message.text.strip() in ['++', '"++"', "Add me"]:
  52.        
  53.         if isinstance(event.source, SourceUser):
  54.             profile = line_bot_api.get_profile(event.source.user_id)
  55.            
  56.             if profile.user_id not in users:
  57.                 users.add(profile.user_id)
  58.                
  59.                 # update users list, should use database
  60.                 with open('./users.txt', 'w', encoding='utf8') as ws:
  61.                     print('\n'.join(list(users)), file=ws)
  62.  
  63.         line_bot_api.reply_message(
  64.             event.reply_token,
  65.             TextSendMessage(text=join_template.format(name=profile.display_name)))
  66.  
  67.        
  68.     else: # reply other messages
  69.         line_bot_api.reply_message(
  70.             event.reply_token,
  71.             TextSendMessage(text="Shut up, I am just a PROTOTYPE."))
  72.  
  73.        
  74. def update_txt():
  75.     # just update my resource, should use database
  76.     with open('./videos.txt', 'w', encoding='utf8') as ws:
  77.         print('\n'.join(urls), file=ws)
  78.        
  79.        
  80. # message to all
  81. def broadcast_video():
  82.     if len(urls) > 0:
  83.         url = urls.pop(0)
  84.         url, title = url.split('\t')
  85.        
  86.         line_bot_api.multicast(list(users),
  87.                                TextSendMessage(text=broadcast_template.format(url=url, title=title)))
  88.         update_txt()
  89.     else:
  90.         print("No URL anymore.")
  91.  
  92. ### The following is the configure for my service
  93.  
  94. # my time schedule
  95. TRIGGER_HOUR = 22
  96.  
  97. # template
  98. join_template = "親愛的{name}您好,已經加你進入英文小組名單囉,歡迎購買阿波羅貓貼圖,喵喵喵。"
  99. broadcast_template = "讀英文囉!\n{title}\n{url}"
  100.  
  101. # get start time
  102. now = datetime.now()
  103. start_time = datetime(now.year, now.month, now.day, TRIGGER_HOUR, 0, 0)
  104. if start_time < now: start_time = start_time.replace(day=now.day+1)
  105.  
  106. ### Setup config for Linebot
  107. class Config(object):
  108.     JOBS = [
  109.         {
  110.             'id': 'broadcast',
  111.             'func': '__main__:broadcast_video',
  112.             'trigger': 'cron',
  113.             'hour': TRIGGER_HOUR,
  114.             'minute': 0,
  115.             'second': 0,
  116.             'start_date': start_time,
  117.             'timezone': timezone('Asia/Taipei')
  118.         }
  119.     ]
  120.  
  121. app.config.from_object(Config())
  122.  
  123. scheduler = APScheduler()
  124. scheduler.api_enabled = True
  125. scheduler.init_app(app)
  126. scheduler.start()
  127.  
  128.  
  129. ### get users set, should use database
  130. users = set()
  131. if os.path.isfile('./users.txt'):
  132.     users = set(open('./users.txt', 'r', encoding='utf8').read().strip().split('\n'))
  133.  
  134. ### get urls, should use database
  135. with open('./videos.txt', 'r', encoding='utf8') as fs:
  136.     urls = fs.read().strip().split('\n')
  137.  
  138.  
  139. if __name__ == "__main__":
  140.     app.run()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top