def auto_message(): # 打开数据库连接 conn = pymysql.connect(host='35.222.24.169', port=3306, user='******', password='******', db='news', charset='utf8') # 使用 cursor() 方法创建一个游标对象 cursor cursor = conn.cursor() # 使用 execute() 方法执行 SQL 查询 cursor.execute("SELECT userid \ FROM user ") data = cursor.fetchall() # 取出userid包成list conn.close() userid = [] for user in data: for i in user: userid.append(i) # print(userid) carouselContent = CarouselContainer.new_from_json_dict( json.loads(foreign_recommend())) flexCarouselSendMeesage = FlexSendMessage(alt_text="foreign", contents=carouselContent) line_bot_api = linebot.LineBotApi( 'mvdB7r737zcCXyzycwFOd6VZN8e1sbcQWkh8v6ue7nUfyU4/O/b2+ROhYazZ21pYoUSBtsnlE4L5Dfwpkdrk2lPJPxEzkdTgzkT5ycPeLZWpAtypNc8ogBLL0LdsRiM4ezuh0uqsssGkLL2aCb4IQwdB04t89/1O/w1cDnyilFU=' ) line_bot_api.multicast(userid, flexCarouselSendMeesage)
def googleSearchFunction(replyToken, text): channelAccessToken = con.get('chatWar', 'CHANNEL_ACCESS_TOKEN') reply_token = replyToken responseText = googleSearch.googleSearch(text) client = linebot.LineBotApi(channelAccessToken) message = linebot.models.TextMessage(text=responseText) client.reply_message(reply_token, message)
def line_push(self, request): if settings.USE_LINE_BOT: import linebot from linebot.models import TextSendMessage context = { 'post': self, } subject = render_to_string('blog/mail/send_latest_notify_message.txt', context, request) line_bot_api = linebot.LineBotApi(settings.LINE_BOT_API_KEY) for push in LinePush.objects.all(): line_bot_api.push_message(push.user_id, messages=TextSendMessage(text=message))
def post(self, request, *args, **kwargs): cache_key = f"chatbot.views.Callbackview.post({self.kwargs['slug']})" cache_time = settings.CACHES['default']['TIMEOUT86400'] golf_club = cache.get(cache_key) if not golf_club: try: golf_club = golf_models.GolfClub.objects.get(slug=self.kwargs['slug']) cache.set(cache_key, golf_club, cache_time) except golf_models.GolfClub.DoesNotExist: raise http.Http404('Invalid golf club') self.line_bot_api = linebot.LineBotApi(golf_club.line_bot_channel_access_token) self.handler = linebot.WebhookHandler(golf_club.line_bot_channel_secret) @self.handler.add(models.MessageEvent, message=models.TextMessage) def handle_message(event): text = event.message.text.strip() text_lowercase = text.lower() cache_key = f'chatbot.membership({event.source.user_id},{golf_club.id})' membership = cache.get(cache_key) # Retrieve LINE user if not membership: try: membership = golf_models.LineUserMembership.objects \ .select_related('line_user', 'customer_group') \ .get(line_user__line_user_id=event.source.user_id, customer_group__golf_club=golf_club) cache.set(cache_key, membership, cache_time) except golf_models.LineUserMembership.DoesNotExist: self.line_bot_api.reply_message( event.reply_token, models.TextSendMessage(text='Invalid Golf Course or LINE ID')) return if match := re \ .compile('New\s"(.+)"\s(\d\d\d\d-\d\d-\d\d)\s(\d\d:\d\d)\s(\d)\sGOLFER\s(\d)\sCART', re.I) \ .match(text): message.command_new(event, self.line_bot_api, match=match, golf_club=golf_club, membership=membership) elif match := re.compile('Settings\s"(.{2,32})"\s([\w.-]+@[\w.-]+)\s([ \d+-]{8,18})\s([a-zA-Z]{2})', re.I) \ .match(text): message.command_settings(event, self.line_bot_api, match=match, golf_club=golf_club, membership=membership)
def handle_line_events(config, events): session = get_db_session(config) try: for event in events: print('line event', event) if event.type == 'join': if event.source.type == 'group': line_group = get_or_create_line_group(session, event.source.group_id) line_bot_api = linebot.LineBotApi(config.bots.line_bot.channel_access_token) line_bot_api.push_message(line_group.group_id, TextSendMessage(text='西卡神降臨,快恭迎!')) if event.type == 'leave': if event.source.type == 'group': delete_line_group(session, event.source.group_id) finally: session.close()
def handle(self, *args, **options): iottalk = dan.Iottalk( dm_name="Dummy_Device", df_list=["Dummy_Control"], d_name="rollcall-notifier", mac=uuid.uuid4().hex, ) iottalk.device_registration_with_retry(os.getenv("IOTTALK_ENDPOINT")) line_api = linebot.LineBotApi(os.getenv("LINE_ACCESS_TOKEN")) try: while True: data = iottalk.pull("Dummy_Control") if data: line_api.broadcast(models.TextSendMessage(data[0])) time.sleep(0.2) finally: iottalk.deregister()
def main(): bot = linebot.LineBotApi(LINE_TOKEN) # message = TextSendMessage(text="hoge") w = Weather(WEATHER_TOKEN) response = w.get_weather_by_city_name("Osaka") json = response.json() icon_id = json["weather"][0]["icon"] icon_url = w.get_icon(icon_id).url message = ImageSendMessage(original_content_url=icon_url, preview_image_url=icon_url) try: bot.push_message(LINE_ID, message) except linebot.exceptions.LineBotApiError as e: print(e.status_code) print(e.request_id) print(e.error.message) print(e.error.details)
def send_push_text_message_line(line_bot_channel_access_token, to, message, **kwargs): quick_reply = None if 'postback_actions' in kwargs: items = [] for action in kwargs['postback_actions']: items.append( models.QuickReplyButton(action=models.PostbackAction( label=action['label'], data=action['data'], display_text=action['display_text']))) quick_reply = models.QuickReply(items=items) line_bot_api = linebot.LineBotApi(line_bot_channel_access_token) line_bot_api.push_message( to, models.TextSendMessage(text=message, quick_reply=quick_reply))
def handle_propagation_task(task_id, config, task_in: schemas.TaskIn, db: Session): mode = task_in.mode if task_in.mode else 'random' if mode == 'random': saying = db.query(models.Saying).order_by(func.random()).first() else: print('尚不支援別的模式...') return if not saying: return if config.bots.line_bot: try: line_bot_api = linebot.LineBotApi(config.bots.line_bot.channel_access_token) line_bot_api.broadcast(TextSendMessage(text=f'{saying.content} - {saying.origin.name}')) for line_group in get_line_groups(db): line_bot_api.push_message(line_group.group_id, TextSendMessage(text=f'{saying.content} - {saying.origin.name}')) except LineBotApiError as e: print('Line Bot 出錯:', e) if config.bots.telegram_bot: bot = telegram.Bot(config.bots.telegram_bot.token) for telegram_group in get_telegram_groups(db): bot.send_message(chat_id=telegram_group.chat_id, text=f'{saying.content} - {saying.origin.name}') if config.bots.slack_bot: if isinstance(config.bots.slack_bot.webhook_url, str): webhook_urls = [config.bots.slack_bot.webhook_url] else: webhook_urls = list(config.bots.slack_bot.webhook_url) for webhook_url in webhook_urls: client = slack_sdk.webhook.WebhookClient(webhook_url) client.send(text=f'{saying.content} - {saying.origin.name}') print(f'任務 {task_id} 完成!')
def handle(self, *args, **options): club = golf_models.GolfClub.objects.get(slug=options['club'][0]) line_rich_menu = {} line_bot_api = linebot.LineBotApi(club.line_bot_channel_access_token) # Delete all rich menus rich_menu_list = line_bot_api.get_rich_menu_list() for rich_menu in rich_menu_list: print(rich_menu.rich_menu_id) line_bot_api.delete_rich_menu(rich_menu.rich_menu_id) # Create rich menu (English-default) rich_menu_id = line_bot_api.create_rich_menu(rich_menu=models.RichMenu( size=models.RichMenuSize(width=2500, height=1686), # 2500x1686, 2500x843, 1200x810, 1200x405, 800x540, 800x270 selected=True, name="rich_menu", chat_bar_text="Menu", areas=[ models.RichMenuArea( bounds=models.RichMenuBounds( x=0, y=0, width=833, height=843), action=models.MessageAction(label='My Booking', text='Booking'), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=833, y=0, width=834, height=843), action=models.URIAction( label='Price Table', uri= f"https://liff.line.me/{club.liff['price']['en']['id']}" ), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=1667, y=0, width=833, height=843), action=models.MessageAction(label='Course', text='Course'), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=0, y=843, width=833, height=843), action=models.MessageAction(label='Promotions', text='Promotions'), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=833, y=843, width=834, height=843), action=models.MessageAction(label='Hot Deals', text='Deals'), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=1667, y=843, width=833, height=843), action=models.MessageAction(label='Coupons', text='Coupons'), ), ])) line_rich_menu['default'] = rich_menu_id line_rich_menu['en'] = rich_menu_id print("rich_menu_id(en)", rich_menu_id) # Upload image and attach it to rich menu with open(Path(f"{options['rich_menu_image_path'][0]}_en.jpg"), 'rb') as f: line_bot_api.set_rich_menu_image(rich_menu_id, 'image/jpeg', f) # Set rich menu to default line_bot_api.set_default_rich_menu(rich_menu_id) # Create rich menu (Korean) rich_menu_id = line_bot_api.create_rich_menu(rich_menu=models.RichMenu( size=models.RichMenuSize(width=2500, height=1686), # 2500x1686, 2500x843, 1200x810, 1200x405, 800x540, 800x270 selected=True, name="rich_menu", chat_bar_text="Menu", areas=[ models.RichMenuArea( bounds=models.RichMenuBounds( x=0, y=0, width=833, height=843), action=models.MessageAction(label='나의 예약', text='Booking'), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=833, y=0, width=834, height=843), action=models.URIAction( label='요금표', uri= f"https://liff.line.me/{club.liff['price']['ko']['id']}" ), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=1667, y=0, width=833, height=843), action=models.MessageAction(label='골프장', text='Course'), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=0, y=843, width=833, height=843), action=models.MessageAction(label='프로모션', text='Promotions'), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=833, y=843, width=834, height=843), action=models.MessageAction(label='핫딜', text='Deals'), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=1667, y=843, width=833, height=843), action=models.MessageAction(label='쿠폰', text='Coupons'), ), ])) line_rich_menu['ko'] = rich_menu_id print("rich_menu_id(ko)", rich_menu_id) # Upload image and attach it to rich menu with open(Path(f"{options['rich_menu_image_path'][0]}_ko.jpg"), 'rb') as f: line_bot_api.set_rich_menu_image(rich_menu_id, 'image/jpeg', f) # Create rich menu (Thai) rich_menu_id = line_bot_api.create_rich_menu(rich_menu=models.RichMenu( size=models.RichMenuSize(width=2500, height=1686), # 2500x1686, 2500x843, 1200x810, 1200x405, 800x540, 800x270 selected=True, name="rich_menu", chat_bar_text="Menu", areas=[ models.RichMenuArea( bounds=models.RichMenuBounds( x=0, y=0, width=833, height=843), action=models.MessageAction(label='My Booking', text='Booking'), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=833, y=0, width=834, height=843), action=models.URIAction( label='Price Table', uri= f"https://liff.line.me/{club.liff['price']['th']['id']}" ), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=1667, y=0, width=833, height=843), action=models.MessageAction(label='Course', text='Course'), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=0, y=843, width=833, height=843), action=models.MessageAction(label='Promotions', text='Promotions'), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=833, y=843, width=834, height=843), action=models.MessageAction(label='Hot Deals', text='Deals'), ), models.RichMenuArea( bounds=models.RichMenuBounds( x=1667, y=843, width=833, height=843), action=models.MessageAction(label='Coupons', text='Coupons'), ), ])) line_rich_menu['th'] = rich_menu_id print("rich_menu_id(th)", rich_menu_id) # Upload image and attach it to rich menu with open(Path(f"{options['rich_menu_image_path'][0]}_en.jpg"), 'rb') as f: line_bot_api.set_rich_menu_image(rich_menu_id, 'image/jpeg', f) ''' # Create rich menu (Japanese) rich_menu_id = line_bot_api.create_rich_menu(rich_menu=models.RichMenu( size=models.RichMenuSize(width=2500, height=1686), # 2500x1686, 2500x843, 1200x810, 1200x405, 800x540, 800x270 selected=True, name="rich_menu", chat_bar_text="Menu", areas=[ models.RichMenuArea( bounds=models.RichMenuBounds(x=0, y=0, width=833, height=843), action=models.MessageAction(label='My Booking', text='Booking'), ), models.RichMenuArea( bounds=models.RichMenuBounds(x=833, y=0, width=834, height=843), action=models.URIAction(label='Price Table', uri=f"https://liff.line.me/{club.liff['price']['jp']['id']}"), ), models.RichMenuArea( bounds=models.RichMenuBounds(x=1667, y=0, width=833, height=843), action=models.MessageAction(label='Course', text='Course'), ), models.RichMenuArea( bounds=models.RichMenuBounds(x=0, y=843, width=833, height=843), action=models.MessageAction(label='Promotions', text='Promotions'), ), models.RichMenuArea( bounds=models.RichMenuBounds(x=833, y=843, width=834, height=843), action=models.MessageAction(label='Hot Deals', text='Deals'), ), models.RichMenuArea( bounds=models.RichMenuBounds(x=1667, y=843, width=833, height=843), action=models.MessageAction(label='Coupons', text='Coupons'), ), ] )) line_rich_menu['jp'] = rich_menu_id print("rich_menu_id(jp)", rich_menu_id) # Upload image and attach it to rich menu with open(Path(f"{options['rich_menu_image_path'][0]}_jp.jpg"), 'rb') as f: line_bot_api.set_rich_menu_image(rich_menu_id, 'image/jpeg', f) # Create rich menu (Chinese) rich_menu_id = line_bot_api.create_rich_menu(rich_menu=models.RichMenu( size=models.RichMenuSize(width=2500, height=1686), # 2500x1686, 2500x843, 1200x810, 1200x405, 800x540, 800x270 selected=True, name="rich_menu", chat_bar_text="Menu", areas=[ models.RichMenuArea( bounds=models.RichMenuBounds(x=0, y=0, width=833, height=843), action=models.MessageAction(label='My Booking', text='Booking'), ), models.RichMenuArea( bounds=models.RichMenuBounds(x=833, y=0, width=834, height=843), action=models.URIAction(label='Price Table', uri=f"https://liff.line.me/{club.liff['price']['cn']['id']}"), ), models.RichMenuArea( bounds=models.RichMenuBounds(x=1667, y=0, width=833, height=843), action=models.MessageAction(label='Course', text='Course'), ), models.RichMenuArea( bounds=models.RichMenuBounds(x=0, y=843, width=833, height=843), action=models.MessageAction(label='Promotions', text='Promotions'), ), models.RichMenuArea( bounds=models.RichMenuBounds(x=833, y=843, width=834, height=843), action=models.MessageAction(label='Hot Deals', text='Deals'), ), models.RichMenuArea( bounds=models.RichMenuBounds(x=1667, y=843, width=833, height=843), action=models.MessageAction(label='Coupons', text='Coupons'), ), ] )) line_rich_menu['cn'] = rich_menu_id print("rich_menu_id(cn)", rich_menu_id) # Upload image and attach it to rich menu with open(Path(f"{options['rich_menu_image_path'][0]}_cn.jpg"), 'rb') as f: line_bot_api.set_rich_menu_image(rich_menu_id, 'image/jpeg', f) ''' # Save rich menu json field club.line_rich_menu = line_rich_menu club.save() self.stdout.write(self.style.SUCCESS('Made rich menu'))
def send_line_bot(user_id): line_bot_api = linebot.LineBotApi('Access_token') line_bot_api.push_message(user_id, TextSendMessage(text=message))
# サードパーティ import flask import linebot from flask import request, abort from linebot import exceptions, models # 自作モジュール from collector import infected_person app = flask.Flask(__name__) # 環境変数取得 YOUR_CHANNEL_ACCESS_TOKEN = os.environ['YOUR_CHANNEL_ACCESS_TOKEN'] YOUR_CHANNEL_SECRET = os.environ['YOUR_CHANNEL_SECRET'] line_bot_api = linebot.LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN) handler = linebot.WebhookHandler(YOUR_CHANNEL_SECRET) text = """\ キーワードにマッチする情報が見つけれらませんでした。<(_ _)>""" @app.route('/corona', methods=['POST']) def receptionist(): signature = request.headers['X-Line-Signature'] body = request.get_data(as_text=True) app.logger.info("Request body: " + body)
import json from django.http import HttpResponse from django.shortcuts import redirect, get_object_or_404 from django.views import generic from django.views.decorators.csrf import csrf_exempt from .models import LinePush, LineMessage import linebot from linebot.models import TextSendMessage line_bot_api = linebot.LineBotApi('アクセストークン') @csrf_exempt def callback(request): """ラインの友達追加時・メッセージ受信時に呼ばれる""" if request.method == 'POST': request_json = json.loads(request.body.decode('utf-8')) events = request_json['events'] line_user_id = events[0]['source']['userId'] # チャネル設定のWeb hook接続確認時にはここ。このIDで見に来る。 if line_user_id == 'Udeadbeefdeadbeefdeadbeefdeadbeef': pass # 友達追加時 elif events[0]['type'] == 'follow': profile = line_bot_api.get_profile(line_user_id) LinePush.objects.create(user_id=line_user_id, display_name=profile.display_name) # アカウントがブロックされたとき
import linebot from django.conf import settings from django.http import ( HttpResponse, HttpResponseForbidden ) from django.utils.decorators import method_decorator from django.views import generic from django.views.decorators.csrf import csrf_exempt from linebot import models from linebot.exceptions import InvalidSignatureError line_bot_api = linebot.LineBotApi(settings.LINE_CHANNEL_ACCESS_TOKEN) handler = linebot.WebhookHandler(settings.LINE_CHANNEL_SECRET) @method_decorator(csrf_exempt, name='dispatch') class CallbackView(generic.View): def post(self, request, *args, **kwargs): if 'X-Line-Signature' in request.headers: signature = request.headers['X-Line-Signature'] body = request.body.decode('utf-8') try: handler.handle(body, signature) except InvalidSignatureError: return HttpResponseForbidden() return HttpResponse('OK') return HttpResponseForbidden()
from linebot.exceptions import InvalidSignatureError from linebot.models import ImageMessage, MessageEvent, TextMessage, TextSendMessage import base64 import requests, json, os, io from io import BytesIO from PIL import Image import numpy as np from keras.preprocessing.image import img_to_array, load_img from keras.models import load_model import gc print('***ライブラリのインポート***') app = Flask(__name__) line_bot_api = linebot.LineBotApi(os.environ['LINE_CHANNEL_ACCESS_TOKEN']) handler = linebot.WebhookHandler(os.environ['LINE_CHANNEL_SECRET']) header = { "Content-Type": "application/json", "Authorization": "Bearer " + os.environ['LINE_CHANNEL_ACCESS_TOKEN'] } # model はグローバルで宣言し、初期化しておく model = None print('****前準備****') @app.route("/callback", methods=['POST']) def callback():