def send_media(event, context): logger.info("Authentication OK.") # LineBotAPIオブジェクトを作成する token = os.getenv('LINE_ACCESS_TOKEN') line_bot_api = LineBotApi(token) try: # twitter 検索で画像と動画の URL オブジェクトの配列を取得 function_name = context.function_name.split('-')[-1] messages = getattr(eval(function_name), function_name)() print('messages') print(messages) if os.getenv('STAGE') == 'prod': for message in messages: line_bot_api.broadcast( message ) else: user_id = os.getenv('USER_ID') for message in messages: line_bot_api.push_message( user_id, message ) except LineBotApiError as e: print(e.status_code) print(e.error.message) print(e.error.details) return {"stautsCode": 200, "body": "OK"}
def sendMessage(messagesToSend, users): f = open('/home/nishimura/public_html/rumor-bot/conf/lineAccessToken.txt') LINE_CHANNEL_ACCESS_TOKEN = f.read() # ファイル終端まで全て読んだデータを返す f.close() line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN) # line_bot_api.push_message("Uf811de50a7725a63c181cf7fc8977ae7", messages=messagesToSend) #id指定して個人に送信するパターン # line_bot_api.multicast(users, messages=messagesToSend) #複数ユーザに送信するには配列でidを渡す line_bot_api.broadcast(messages=messagesToSend) #登録者全員に送信
def send_line_broadcast_message(msg: str) -> bool: line_bot_api = LineBotApi(channel_access_token='알람을_전송할_line_봇_토큰') try: line_bot_api.broadcast(messages=TextSendMessage(text=msg)) print('[{}] line broadcast message sent successfully'.format(datetime.now())) return True except LineBotApiError as e: print('[{}] {}'.format(datetime.now(), e)) return False
def send_line_message(msg): ACCESS_TOKEN = 'ER+KnU1nE9Z1bDZ4dwNCz7INXVT+9zzFKt4RAzU2e/c2G0c9rB8EhcAFeHEbODRlVume3fQofmza9p+N6pdBP0cXiyNrO71bs89HV1S54X7234j+dGdukvhtBzgdCEv+Cf4VtpkVeIV8r1i0lC9gVQdB04t89/1O/w1cDnyilFU=' line_bot_api = LineBotApi(ACCESS_TOKEN) line_bot_api.broadcast(TextSendMessage(text=msg)) path = PATH with open(path, mode='w') as file: writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') writer.writerow([now, msg])
def sendLINEMessage(msg: str): ACCESS_TOKEN = me_config["LINE"]["token"] line_bot_api = LineBotApi(ACCESS_TOKEN) sent=False if("users" in me_config["LINE"]): users = me_config["LINE"]["users"] line_bot_api.multicast(users,TextSendMessage(text=msg)) sent=True if("group" in me_config["LINE"]): group = me_config["LINE"]["group"] line_bot_api.push_message(group,TextSendMessage(text=msg )) sent=True if not sent: line_bot_api.broadcast(TextSendMessage(text=msg))
def create_flexmessage(config, railways_map): railways = railways_map.delay_railways flexmessage = json.load(open(config['LINE']['flexmessage_json'], 'r')) url = flexmessage["contents"]["hero"]["url"] dirname = os.path.dirname(url) basename = os.path.basename(railways_map.png) flexmessage["contents"]["hero"]["url"] = os.path.join(dirname, basename) if railways == []: tmp_dict = {"type": "text", "text": '遅延はありません'} flexmessage["contents"]["body"]["contents"].append(tmp_dict) else: tmp_dict = {"type": "text", "text": '遅延路線:'} flexmessage["contents"]["body"]["contents"].append(tmp_dict) # 変換 railways = replace_railway(railways, config['MAP']['railway_path']) # メッセージ追加 for railway in railways: tmp_dict = {"type": "text", "text": ' ' + railway} flexmessage["contents"]["body"]["contents"].append(tmp_dict) map_html = config['MAP']['html'] with open(map_html, mode='r+', encoding='utf-8') as f: soup = BeautifulSoup(f.read(), 'html.parser') image_tag = soup.new_tag('meta', property="og:image", content=railways_map.png) title_tag = soup.new_tag('meta', property="og:title", content="TrainInformation") description_tag = soup.new_tag('meta', property="og:description", content="please tap this message") soup.find('head').append(image_tag) soup.find('head').append(title_tag) soup.find('head').append(description_tag) with open(map_html, 'w') as f: f.write(str(soup)) container_obj = FlexSendMessage.new_from_json_dict(flexmessage) line_bot_api = LineBotApi(os.environ['LINE_ACCESS_TOKEN_TEST']) line_bot_api.broadcast(messages=container_obj) return True
def main(): line_bot_api = LineBotApi(channel_access_token) handler = WebhookHandler(channel_secret) flex_message = FlexSendMessage(alt_text='会議開催のお知らせです。', contents=define) if line_bot_api.broadcast(flex_message): print("Send Success!")
def term(mysql, date, court_number, term_number, availability): res = mysql.get(date, court_number, term_number) if res is None: mysql.create(date, court_number, term_number, availability) return True if res: mysql.update(date, court_number, term_number, availability) return True if not res: if availability: line_bot_api = LineBotApi(os.getenv("LINE_CHANNEL_ACCESS_TOKEN")) messages = TextSendMessage( text=f"{str(date)}に{court_number}番コートで{term_number}に空きができました。") line_bot_api.broadcast(messages=messages) print("通知") mysql.update(date, court_number, term_number, availability) return True
def sendLINEMessage(conf, msg: dict): ACCESS_TOKEN = conf["LINE"]["token"] line_bot_api = LineBotApi(ACCESS_TOKEN) text=msg["text"] sent=False if("users" in conf["LINE"]): users = conf["LINE"]["users"] line_bot_api.multicast(users,TextSendMessage(text=text)) sent=True if("group" in conf["LINE"]): group = conf["LINE"]["group"] line_bot_api.push_message(group,TextSendMessage(text=text )) sent=True if not sent: line_bot_api.broadcast(TextSendMessage(text=text))
class Locker(object): def __init__(self): #登録済みNFC IDの読み取り self.id_list = os.environ["NFC_ID"].split(":") #GPIOピンをプルダウン入力に設定 self.gp_in_yellow = 16 self.gp_in_red = 25 self.gp_in_green = 24 self.gp_in_blue = 23 #GPIO4を制御パルスの出力に設定 self.gp_out = 4 self.if_open = True #LINE Notify用のアクセストークン access_token = os.environ["LINE_NOTIFY_KEY"] self.bot = LINENotifyBot(access_token=access_token) GPIO.setmode(GPIO.BCM) #アンロックピンのセットアップ GPIO.setup(self.gp_in_yellow, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(self.gp_in_yellow, GPIO.RISING, callback=self.callback_open, bouncetime=1000) #ロックピンのセットアップ GPIO.setup(self.gp_in_red, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(self.gp_in_red, GPIO.RISING, callback=self.callback_close, bouncetime=1000) #補助ピンAのセットアップ GPIO.setup(self.gp_in_green, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(self.gp_in_green, GPIO.RISING, callback=self.callback_wait_lock, bouncetime=1000) #補助ピンBのセットアップ GPIO.setup(self.gp_in_blue, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(self.gp_in_blue, GPIO.RISING, callback=self.callback_donki, bouncetime=1000) #出力ピンのセットアップ GPIO.setup(self.gp_out, GPIO.OUT) servo(self.gp_out, GPIO, 0) # LINE BOT APIの設定 self.wait = 0 self.line_bot_api = LineBotApi(os.environ["YOUR_CHANNEL_ACCESS_TOKEN"]) self.client = mqtt.Client() # クラスのインスタンス(実体)の作成 self.client.on_connect = self.on_connect # 接続時のコールバック関数を登録 self.client.on_disconnect = self.on_disconnect # 切断時のコールバックを登録 self.client.on_message = self.on_message # メッセージ到着時のコールバック self.client.username_pw_set(os.environ["USERNAME_PW_SET"]) self.client.tls_set(os.environ["TLS_SET"]) self.client.connect(os.environ["CONNECT_URL"], 8883, 60) self.client.loop_start() self.send_line_msg('システムを起動するよ!') def exec(self): cr = reader(self.id_list) while True: try: self.client.on_message # cr.read_id() #if self.if_open: # self.callback_close(0) #else: # self.callback_open(0) if self.wait == 1: self.callback_open(0) self.wait = 0 elif self.wait == 2: self.callback_close(0) self.wait = 0 except KeyboardInterrupt: #Ctrl+Cキーが押して, GPIO.cleanup() #GPIOをクリーンアップし, sys.exit() #プログラムを終了 self.send_line_msg('システムが終了しました') def callback_open(self, channel): servo(self.gp_out, GPIO, 90) #サーボモータを90度に動作 servo(self.gp_out, GPIO, 0) #サーボモータを0度に動作 self.if_open = True self.send_line_msg('あけたよ!') #self.bot.send(message = "解錠しました") def callback_close(self, channel): servo(self.gp_out, GPIO, -90) #サーボモータを-90度に動作 servo(self.gp_out, GPIO, 0) #サーボモータを0度に動作 self.if_open = False self.send_line_msg('しめたよ!') #self.bot.send(message = "施錠しました") def callback_costco(self, channel): self.send_line_msg('Costco行かね?') #self.bot.send(message = "Costco行かね?") def callback_donki(self, channel): self.send_line_msg('ドンキ行かね?') #self.bot.send(message = "ドンキ行かね?") def callback_wait_lock(self, channel): self.send_line_msg('5秒後に施錠します') #self.bot.send(message = "5秒後に施錠します") time.sleep(5) self.callback_close(0) # ブローカーに接続できたときの処理 def on_connect(self, client, userdata, flag, rc): print('[autoLocker.py] Connected with result code ' + str(rc)) # 接続できた旨表示 self.client.subscribe('Genkan_doa/raspie') # subするトピックを設定 # ブローカーが切断したときの処理 def on_disconnect(self, client, userdata, flag, rc): if rc != 0: print('[autoLocker.py] Unexpected disconnection.') def send_line_msg(self, msg): self.line_bot_api.broadcast(TextSendMessage(text=msg)) # メッセージが届いたときの処理 def on_message(self, client, userdata, msg): get_msg = msg.payload.decode('utf-8') if get_msg == 'on': self.wait = 1 elif get_msg == 'off': self.wait = 2
#!/usr/bin/env python # -*- coding: utf-8 -*- """Test script """ from linebot import LineBotApi from linebot.models import TextSendMessage from linebot.exceptions import LineBotApiError CHANNEL_ACCESS_TOKEN = 'add token here' line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN) try: line_bot_api.broadcast(TextSendMessage(text='This is a test')) except LineBotApiError as e: print("Error {}".format(e))
def line_bot(conf, q_callback): channel, secret = conf.linebot.split(',') from flask import Flask, request, abort from linebot import (LineBotApi, WebhookHandler) from linebot.exceptions import (InvalidSignatureError, LineBotApiError) from linebot.models import ( MessageEvent, TextMessage, TextSendMessage, ) app = Flask(__name__) line_bot_api = LineBotApi(channel) handler = WebhookHandler(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: print( "Invalid signature. Please check your channel access token/channel secret." ) abort(400) return 'OK' @handler.add(MessageEvent, message=TextMessage) def handle_message(event): q = event.message.text print('q:', q) a = q_callback(event.source.sender_id, q) if a == '': a = '<empty>' try: line_bot_api.reply_message(event.reply_token, TextSendMessage(text=a)) except LineBotApiError: # time out might happen line_bot_api.push_message(event.source.sender_id, TextSendMessage(text=a)) line_bot_api.broadcast( TextSendMessage( text= 'GPT-3 is up again. /reset [scene (multiline)] to reset your conversation. This system might be unstable. GPT-3 takes several seconds to process a request.\nMessages starting with / will be regarded as system commands.' )) app.run(threaded=False)
def ntr_handler(data: dict, linebot_api: LineBotApi) -> bool: if "NTR_TOKEN" in data and data["NTR_TOKEN"] == NTR_TOKEN: linebot_api.broadcast(TextMessage(text=data['txt'])) return True return False
def send_line(message): line_bot_api = LineBotApi(MASSAGE_API_TOKEN) messages = TextSendMessage(text=message) line_bot_api.broadcast(messages=messages)
from linebot import (LineBotApi, WebhookHandler) from linebot.models import ( MessageEvent, TextMessage, TextSendMessage, ) import config config = config.get_config() ACCESS_TOKEN = config["LINE"]["token"] SECRET = config["LINE"]["channel_secret"] line_bot_api = LineBotApi(ACCESS_TOKEN) sent = False if ("users" in config["LINE"]): users = config["LINE"]["users"] line_bot_api.multicast( users, TextSendMessage(text="Line Test Message to Multi users")) sent = True if ("group" in config["LINE"]): group = config["LINE"]["group"] line_bot_api.push_message( group, TextSendMessage(text="Line Test Message to group")) sent = True if not sent: line_bot_api.broadcast(TextSendMessage(text='Hello World! broadcast'))
def line_bot(value): line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN) line_bot_api.broadcast(TextSendMessage(text=value))
class costco: def __init__(self): logging.basicConfig(level=logging.INFO, format="%(asctime)s, %(levelname)s: %(message)s", \ datefmt="%Y-%m-%d %H:%M:%S") configFileName = "config.json" if not os.path.isfile(configFileName): print("could not find", configFileName) exit() productFileName = "product.json" if not os.path.isfile(productFileName): print("could not find", productFileName) exit() # 讀取設定 with open(configFileName, "r", encoding="utf-8") as json_file: config = json.load(json_file) # 設定 Line API self.line_bot_token = config["line"][ "line_bot_channel_access_token"] # 設定信箱 self.server = config["email"]["server"] self.port = config["email"]["port"] self.user = config["email"]["user"] self.password = config["email"]["password"] self.from_addr = config["email"]["from_addr"] self.to_addr = config["email"]["to_addr"] # 設定等待時間 self.next_search_time = config["time"]["next_search_time"] self.continuous = config["time"]["continuous"] # 設定 user-agent self.USER_AGENT_LIST = config["agent"]["user-agent"] # 設定目標商品 self.product = list() with open(productFileName, "r", encoding="utf-8") as json_file: config = json.load(json_file) for item in config: # 檢查網址為商品頁面或分類列表 # 切割網址取得商品編號 if item["url"].rsplit("/", 2)[1] == "p": item["id"] = item["url"].rsplit("/", 1)[1] else: item["id"] = None item["status"] = 0 self.product.append(item) self.line_bot_api = LineBotApi(self.line_bot_token) self.message = ["商品下架通知", "商品上架通知(無庫存)", "商品上架通知(有庫存)"] ''' 商品狀態 0 :未上架(分類清單中未出現) 1 :有上架但無庫存(分類清單中有出現或商品網頁存在,但加入購物車按鈕不存在) 2 :有上架且"可能"有庫存(分類清單中有出現或商品網頁存在,且加入購物車按鈕存在) ''' def start(self): while True: self.nowtime = datetime.now(pytz.timezone("Asia/Taipei")) if self.check_time(): for item in self.product: result = self.search(item) if result != item["status"]: item["status"] = result logging.info(item["title"] + " " + item["url"]) self.send_line(item) self.send_email(item) time.sleep(random.randint(10, self.next_search_time)) # 爬取資料,檢查按鈕是否存在 def search(self, item): header = {"user-agent": random.choice(self.USER_AGENT_LIST)} with requests.get(item["url"], headers=header) as res: soup = BeautifulSoup(res.text, "lxml") ''' 商品頁面存在,可以找到 addToCartButton 商品頁面不存在則會自動跳回分類列表,若分類列表存在商品,可能可以找到 add-to-cart-button-xxxxxx 出現"加入購物車"按鈕不代表一定有庫存 若不知道商品網址或編號,只有商品分類網址跟商品名稱,就直接搜尋名稱,但無法檢查按鈕 ''' if item["id"] != None and (soup.find(id="addToCartButton") != None or \ soup.find(id=("add-to-cart-button-" + item["id"])) != None): return 2 elif item["title"] in res.text: return 1 return 0 # 自動加入購物車 def add_to_cart(self): pass def checkout(self): pass # 自訂時間範圍檢查 def check_time(self): if self.continuous: return True elif 8 <= self.nowtime.hour <= 22: return True return False # 寄信通知 def send_email(self, item): text = self.nowtime.strftime( "%Y-%m-%d %H:%M:%S ") + item["title"] + "\n" + item["url"] msg = MIMEText(text, "plain", "utf-8") msg["From"] = Header("好市多爬蟲", "utf-8") msg["To"] = Header(self.to_addr, "utf-8") msg["Subject"] = Header(self.message[item["status"]], "utf-8") with smtplib.SMTP(self.server, self.port) as smtp: smtp.ehlo() smtp.starttls() smtp.login(self.user, self.password) ret = smtp.sendmail(self.from_addr, self.to_addr, msg.as_string()) if ret == {}: logging.info("郵件傳送成功") return True logging.info("郵件傳送失敗") return False # 傳line通知 def send_line(self, item): text = self.message[item["status"]] + "\n" + \ self.nowtime.strftime("%Y-%m-%d %H:%M:%S") + "\n" + item["title"] + "\n" + item["url"] try: self.line_bot_api.broadcast(TextSendMessage(text=text)) except LineBotApiError as e: print(e)
def send_line_message(msg): line_bot_api = LineBotApi(ACCESS_TOKEN) line_bot_api.broadcast(TextSendMessage(text=msg))
# "size": "lg", # "align": "end", # "gravity": "center", # "contents": [] # } # ] # } # ] # } # ] # }, # "footer": { # "type": "box", # "layout": "vertical", # "contents": [ # { # "type": "text", # "text": "引用:Yahoo!天気", # "size": "xxs", # "margin": "xxl", # "contents": [] # } # ] # } # } # } # result = FlexSendMessage.new_from_json_dict(message) result = FlexSendMessage.new_from_json_dict(info) line_bot_api.broadcast(messages=result)
class LYCLineBot(BaseBot): def __init__(self, access_token, secret): self.line_bot_api = LineBotApi(access_token) self.handler = WebhookHandler(secret) self.parser = WebhookParser(secret) def send_message(self, text, user_id): self.line_bot_api.push_message(user_id, TextSendMessage(text=text)) return "send" def boardcast(self, text): self.line_bot_api.broadcast(TextSendMessage(text=text)) return "broadcast" def reply_message(self, text, body, signature): try: events = self.parser.parse(body, signature) for event in events: return_message = self.special_reply(event.message) # 沒有特殊處理過的回應, 解析一下訊息在處理回應 if not return_message: return_message = self.analysis_message( event.message, user_id=event.source.sender_id) logger.info(f'return message: {return_message}') self.line_bot_api.reply_message(event.reply_token, return_message) except InvalidSignatureError as e: return f"authorization failed: {e.error.message}" except LineBotApiError as e: return e.error.message else: return "OK" def user_profile(self, user_id): line_profile = self.line_bot_api.get_profile(user_id) if not line_profile: return None profile = UserProfile() profile.id = line_profile.user_id profile.name = line_profile.display_name profile.description = line_profile.status_message profile.picture = line_profile.picture_url return profile def analysis_message(self, message, *args, **kwargs): """解析使用者傳的訊息來決定回傳什麼東西給使用者 Arguments: message {[MessageEvent.Message]} -- [the message event from user pass] Returns: [SendMessage] -- [the message what postback to the user.] """ # 解析是不是有符合觸發事件 if message.type == "text": seg_list = ", ".join(jieba.cut(message.text)).split(', ') logger.info(f'vocabulary {seg_list}') match_event_message = analyzer.match(seg_list, *args, **kwargs) match_event_message = list( filter(lambda x: x is not None, match_event_message)) if match_event_message and len(match_event_message) > 0: logger.info(fr'reply message: {match_event_message}') return TextSendMessage(text=''.join(match_event_message)) # 沒有就去當鸚鵡吧 allow_message_type = { "text": self.reply_by_text, "sticker": self.reply_by_sticker } func = allow_message_type.get(message.type, self.reply_default) return func(message) def reply_by_text(self, message): """reply a text Arguments: message {string} -- request message Returns: string -- response message """ return TextSendMessage(text=message.text) def reply_by_sticker(self, message): """reply by a sticker Arguments: message {string} -- request message Returns: string -- response sticker. """ if int(message.package_id) > 4: return TextSendMessage(text="中文豪難喔,公蝦聽謀捏。") return StickerSendMessage(package_id=message.package_id, sticker_id=message.sticker_id) def reply_default(self, message): return TextSendMessage(text="中文豪難喔,公蝦聽謀捏。") def template_buttons(self, message): """produce template with buttons Arguments: message {[MessageEvent.Message]} -- [the message event from user pass] """ buttons_template_message = TemplateSendMessage( alt_text='Buttons template', template=ButtonsTemplate( thumbnail_image_url='https://i.imgur.com/ZgVAAMV.jpg', title='LYC電玩展', text='您今天想看什麼任天堂Switch遊戲', actions=[ PostbackTemplateAction(label='最新的', text='最新的', data='action=buy&itemid=1'), MessageTemplateAction(label='特價中的', text='特價中的'), URITemplateAction( label='我自己看吧', uri='https://lycnsbot.herokuapp.com/games') ])) return buttons_template_message def template_confirm(self, message): """produce template with confirm button Arguments: message {[MessageEvent.Message]} -- [the message event from user pass] """ confirm_template_message = TemplateSendMessage( alt_text='Confirm template', template=ConfirmTemplate( text='你準備好買更多的任天堂了嗎?', actions=[ PostbackTemplateAction(label='當然啊', text='我要買任天堂Switch', data='action=buy&itemid=1'), MessageTemplateAction(label='不買行嗎', text='我不買任天堂Switch') ])) return confirm_template_message def template_carousel_buttons(self, message): """produce template with carousel buttons Arguments: message {[MessageEvent.Message]} -- [the message event from user pass] """ carousel_template_message = TemplateSendMessage( alt_text='Carousel template', template=CarouselTemplate(columns=[ CarouselColumn( thumbnail_image_url='https://i.imgur.com/njZeeBz.jpg', title='Splatoon 2', text='花枝會打漆彈耶', actions=[ MessageTemplateAction(label='哇嗚好像很好玩', text='真的不錯玩'), MessageTemplateAction(label='我覺得不行', text='你不行? 你身上哪裡不行'), URITemplateAction( label='現在價錢如何', uri='https://eshop-prices.com/games/260-splatoon-2' ) ]), CarouselColumn( thumbnail_image_url='https://i.imgur.com/p3ozN9s.jpg', title='The Legend Of Zelda-Breath Of The Wild', text='薩爾達傳說之精神時光屋', actions=[ MessageTemplateAction(label='哇嗚好像很好玩', text='真的不錯玩'), MessageTemplateAction(label='我覺得不行', text='你不行? 你身上哪裡不行'), URITemplateAction( label='現在價錢如何', uri= 'https://eshop-prices.com/games/378-the-legend-of-zelda-breath-of-the-wild' ) ]) ])) return carousel_template_message def template_carousel_images(self, message): """produce template with carousel images Arguments: message {[MessageEvent.Message]} -- [the message event from user pass] """ image_carousel_template_message = TemplateSendMessage( alt_text='ImageCarousel template', template=ImageCarouselTemplate(columns=[ ImageCarouselColumn( image_url='https://i.imgur.com/njZeeBz.jpg', action=PostbackAction(label='Splatoon 2 漆彈大作戰', text='快來打漆彈', data='action=buy&itemid=1')), ImageCarouselColumn( image_url='https://i.imgur.com/p3ozN9s.jpg', action=PostbackAction(label='薩爾達傳說之精神時光屋', text='人馬? 給虐嗎?', data='action=buy&itemid=2')) ])) return image_carousel_template_message def special_reply(self, message): """特殊處理的回覆訊息 Arguments: message {[MessageEvent.Message]} -- [the message event from user pass] Returns: [SendMessage] -- [the special message what postback to the user.] """ match_stickers = { "1-10": self.template_buttons, "1-2": self.template_confirm, "1-4": self.template_carousel_buttons, "1-13": self.template_carousel_images } if message.type == "sticker": key = "{0}-{1}".format(message.package_id, message.sticker_id) func = match_stickers.get(key, lambda s: None) logger.info(func) return func(message) return None
def send_message(message): line_bot_api = LineBotApi(config.MORNING_AI_TOKEN) line_bot_api.broadcast(TextSendMessage(text=message))
class TestSendTestMessage(unittest.TestCase): def setUp(self): self.tested = LineBotApi('channel_secret') # test data self.text_message = TextSendMessage(text='Hello, world') self.message = [{"type": "text", "text": "Hello, world"}] @responses.activate def test_push_text_message(self): responses.add(responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', json={}, status=200) self.tested.push_message('to', self.text_message) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') self.assertEqual(json.loads(request.body), { "to": "to", 'notificationDisabled': False, "messages": self.message }) @responses.activate def test_reply_text_message(self): responses.add(responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', json={}, status=200) self.tested.reply_message('replyToken', self.text_message) request = responses.calls[0].request self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') self.assertEqual(request.method, 'POST') self.assertEqual( json.loads(request.body), { "replyToken": "replyToken", 'notificationDisabled': False, "messages": self.message }) @responses.activate def test_multicast_text_message(self): responses.add(responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', json={}, status=200) self.tested.multicast(['to1', 'to2'], self.text_message) request = responses.calls[0].request self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') self.assertEqual(request.method, 'POST') self.assertEqual( json.loads(request.body), { "to": ['to1', 'to2'], 'notificationDisabled': False, "messages": self.message }) @responses.activate def test_broadcast_text_message(self): responses.add(responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/broadcast', json={}, status=200) self.tested.broadcast(self.text_message) request = responses.calls[0].request self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/broadcast') self.assertEqual(request.method, 'POST') self.assertEqual(json.loads(request.body), { 'notificationDisabled': False, "messages": self.message }) # call with notification_disable=True self.tested.broadcast(self.text_message, notification_disabled=True) request = responses.calls[1].request self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/broadcast') self.assertEqual(request.method, 'POST') self.assertEqual(json.loads(request.body), { 'notificationDisabled': True, "messages": self.message })
from linebot import (LineBotApi, WebhookHandler) from linebot.models import TextSendMessage # 創造 Line bot api line_bot_api = LineBotApi( 'nbE0Yqi3KGYDpWH579IgAtS1ggxub+PUUgy0tUvNlkKAfIoRdo4D2GOiaPOQgqA6wr47BQdZ/6S4C/uhLmphZ2EpCs7xHhRwVC2kzpmdwVIyAnWRxdxEw3JKJvl1uY64mLntrp2GqPwUJccqeEc4owdB04t89/1O/w1cDnyilFU=' ) handler = WebhookHandler('784899c6df4a550a6b1d11f2fb5ad363') line_bot_api.push_message(to="Ua899229ef9500a14368b30bbac9efa10", messages=[TextSendMessage("hihi :D")]) line_bot_api.broadcast(TextSendMessage("有內鬼、停止交易"))
def post_line_message(token, message): line_bot_api = LineBotApi(token) res = line_bot_api.broadcast(TextSendMessage(text=message))
def send_line(content): access_token = ******** #Channel access token を記入 line_bot_api = LineBotApi(access_token) line_bot_api.broadcast(TextSendMessage(text=content))
textFile = Path("rtx3070.text") line_bot_api = LineBotApi(os.environ["line_channel_token"]) url = "https://shop.tsukumo.co.jp/search/c20:2018:2018200:201820088000400/?keyword=3070" html = requests.get(url) soup = BeautifulSoup(html.content, "html.parser") get_class = soup.find( class_="search-box__product-list search-default__product-list mb20__common" ) get_text = get_class.find_all(class_="search-box__product") text_only = [x.text for x in get_text] text_only = [x.replace("\n", "") for x in text_only] text_only = [x.replace("\xa0", "") for x in text_only] text_only = str(text_only) old = open(textFile, encoding="UTF-8") old_text = old.read() if (text_only == old_text): line_bot_api.broadcast(TextSendMessage(text='更新はありまsん')) else: f = open(textFile, "w", encoding="UTF-8") f.writelines(text_only) f.close line_bot_api.broadcast(TextSendMessage(text='3070更新された')) line_bot_api.broadcast(TextSendMessage(text=url))
def send_line_msg(msg): line_bot_api = LineBotApi("your linebot api") line_bot_api.broadcast(TextSendMessage(text=msg))
elif event.message.text == 'admin:debug mode off' and get_author == True: dev_debugging_in_process = False text = 'dev_debugging_in_process is {status}'.format( status=dev_debugging_in_process) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=status_text+text)) return None # set the availablility elif (event.message.text == 'break admin mode') and (get_author == True): get_author = False line_bot_api.reply_message(event.reply_token, TextSendMessage( 'Getting out from ADMIN mode . get_author is {status}'.format(status = get_author))) return None else: return None ### methods line_bot_api.broadcast(TextSendMessage(text='im ready! by global')) # boardcast when already deployed # 監聽所有來自 /callback 的 Post Request @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:
hero=ImageComponent( url= "https://vos.line-scdn.net/bot-designer-template-images/bot-designer-icon.png", size="full", aspect_ratio="1.51:1", aspect_mode="fit", action=None), body=BoxComponent( layout="vertical", contents=[ TextComponent( text='text', align='center', gravity='center', contents=[SpanComponent(text='体調登録', weight="bold")]), TextComponent(text='text', align='center', gravity='center', offsetTop='10px', contents=[SpanComponent(text='本日の体調を登録してください')]) ]), #Body footer=BoxComponent( layout="vertical", contents=[ ButtonComponent(action=URIAction( label="登録する", uri="https://liff.line.me/1655595024-8ZXeW3Ww")) ]) #Footer )) line_bot_api.broadcast(messages=message)