[LINE] Messaging APIで、テキスト以外のレスポンスを送る

modelをTextMessageではなく、TemplateMessageに変更する
公式ドキュメントを参考にする
https://developers.line.biz/en/reference/messaging-api/#imagemap-message
SDKのモデル一覧はこちら
https://github.com/line/line-bot-sdk-php/blob/master/examples/KitchenSink/src/LINEBot/KitchenSink/EventHandler/MessageHandler/TextMessageHandler.php

  $template = array('type'    => 'confirm',
                  'text'    => 'テキストメッセージ。最大240文字',
                  'actions' => array(
                                 array('type'=>'message', 'label'=>'yes', 'text'=>'yesを押しました' ),
                                 array('type'=>'message', 'label'=>'no',  'text'=>'noを押しました' )
                                )
                );
  $message = new \LINE\Clients\MessagingApi\Model\TemplateMessage(['type' => 'template','altText'  => '代替テキスト','template' => $template]);
  $request = new \LINE\Clients\MessagingApi\Model\ReplyMessageRequest([
    'replyToken' => $replyToken,
    'messages' => [$message],
  ]);
  $response = $messagingApi->replyMessage($request);

LINE側の挙動は確認できたので、あとはMySQLのCRUDとChatGPTのレスポンスの確認

LINE Messaging APIで複数レスポンスする

複数のメッセージを送信したい場合は、messagesを配列にする。

$message = new \LINE\Clients\MessagingApi\Model\TextMessage(['type' => 'text','text' => $message->{"text"}]);
$userId = new \LINE\Clients\MessagingApi\Model\TextMessage(['type' => 'text','text' => $userId]);
$request = new \LINE\Clients\MessagingApi\Model\ReplyMessageRequest([
    'replyToken' => $replyToken,
    'messages' => [$message, $userId],
]);
$response = $messagingApi->replyMessage($request);

1つのリクエストでreplyTokenを複数作ることはできないので、以下のようにレスポンスを複数は書けない。この場合、最初のレスポンスしか表示されない。

$message = new \LINE\Clients\MessagingApi\Model\TextMessage(['type' => 'text','text' => $message->{"text"}]);
$request = new \LINE\Clients\MessagingApi\Model\ReplyMessageRequest([
    'replyToken' => $replyToken,
    'messages' => [$message],
]);
$response = $messagingApi->replyMessage($request);

$userId = new \LINE\Clients\MessagingApi\Model\TextMessage(['type' => 'text','text' => $userId]);
$request = new \LINE\Clients\MessagingApi\Model\ReplyMessageRequest([
    'replyToken' => $replyToken,
    'messages' => [$userId],
]);
$response = $messagingApi->replyMessage($request);

LINE Messaging APIでUserIDを取得する

webhookイベントオブジェクトの構造を参考にUserIDを取得する

### webhookイベントオブジェクト
https://developers.line.biz/ja/reference/messaging-api/#webhook-event-objects
これを見ると、sourceのuserIdがあるので、これをキーに出来そう

{
  "destination": "xxxxxxxxxx",
  "events": [
    {
      "type": "message",
      "message": {
        "type": "text",
        "id": "14353798921116",
        "text": "Hello, world"
      },
      "timestamp": 1625665242211,
      "source": {
        "type": "user",
        "userId": "U80696558e1aa831..."
      },
      "replyToken": "757913772c4646b784d4b7ce46d12671",
      "mode": "active",
      "webhookEventId": "01FZ74A0TDDPYRVKNK77XKC3ZR",
      "deliveryContext": {
        "isRedelivery": false
      }
    },
    {
      "type": "follow",
      "timestamp": 1625665242214,
      "source": {
        "type": "user",
        "userId": "Ufc729a925b3abef..."
      },
      "replyToken": "bb173f4d9cf64aed9d408ab4e36339ad",
      "mode": "active",
      "webhookEventId": "01FZ74ASS536FW97EX38NKCZQK",
      "deliveryContext": {
        "isRedelivery": false
      }
    },
    {
      "type": "unfollow",
      "timestamp": 1625665242215,
      "source": {
        "type": "user",
        "userId": "Ubbd4f124aee5113..."
      },
      "mode": "active",
      "webhookEventId": "01FZ74B5Y0F4TNKA5SCAVKPEDM",
      "deliveryContext": {
        "isRedelivery": false
      }
    }
  ]
}

ソースコード上ではこのように取得する

$message = $jsonObj->{"events"}[0]->{"message"}; 
$userID = $jsonObj->{"events"}[0]->{"source"}->{"userId"}; 

さあ、mysqlの構造をどうするかですね。
その前にレスポンスのバリエーションを確認したい。

line-bot-sdk-phpとreplyToken

LINE Messaging APIを使用した開発をやります。
$ php composer.phar require linecorp/line-bot-sdk
$ php composer.phar require guzzlehttp/guzzle

こちらでは上手くいかない

require("vendor/autoload.php");

use LINE\LINEBot\Constant\HTTPHeader;
use LINE\LINEBot\HTTPClient\CurlHTTPClient;
use LINE\LINEBot;

$channel_access_token = 'xxxx';
$channel_secret = 'xxxx';

$http_client = new CurlHTTPClient($channel_access_token);
$bot = new LINEBot($http_client, ['channelSecret' => $channel_secret]);
$signature = $_SERVER['HTTP_' . HTTPHeader::LINE_SIGNATURE];
$http_request_body = file_get_contents('php://input');
$events = $bot->parseEventRequest($http_request_body, $signature);
$event = $events[0];

$reply_token = $event->getReplyToken();
$reply_text = $event->getText();
$bot->replyText($reply_token, $reply_text);

Githubを見ながら少し内容を変更します。SDKのバージョンによってライブラリのclass構成が変わっているようです。
https://github.com/line/line-bot-sdk-php
replyTokenは、{“events”}[0]に入っている。line-bot-sdk-phpのsampleを見ても全然わからなかったので、凄い時間がかったw

ini_set("display_errors", 1);
error_reporting(E_ALL);
require("vendor/autoload.php");

$jsonString = file_get_contents('php://input'); error_log($jsonString); 
$jsonObj = json_decode($jsonString); $message = $jsonObj->{"events"}[0]->{"message"}; 
$replyToken = $jsonObj->{"events"}[0]->{"replyToken"};

$client = new \GuzzleHttp\Client();
$config = new \LINE\Clients\MessagingApi\Configuration();
$config->setAccessToken('');
$messagingApi = new \LINE\Clients\MessagingApi\Api\MessagingApiApi(
  client: $client,
  config: $config,
);

$message = new \LINE\Clients\MessagingApi\Model\TextMessage(['type' => 'text','text' => $message->{"text"}]);
$request = new \LINE\Clients\MessagingApi\Model\ReplyMessageRequest([
    'replyToken' => $replyToken,
    'messages' => [$message],
]);
$response = $messagingApi->replyMessage($request);

Ubuntu22.04にPHPとMySQLをインストールする

$ sudo apt update

### PHP
$ sudo apt install php libapache2-mod-php php-mysql
$ php -v
PHP 8.1.2-1ubuntu2.14 (cli) (built: Aug 18 2023 11:41:11) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.2, Copyright (c) Zend Technologies
with Zend OPcache v8.1.2-1ubuntu2.14, Copyright (c), by Zend Technologies

### MySQL
$ sudo apt install mysql-server

### composer.phar
$ curl -sS https://getcomposer.org/installer | php

[bitcoin] bitcoincoreのファイル構造 [その1]

まずGithubから bitcoincore のソースコードを clone してきます。
github上で見てもいいんですが、なんとなくローカルに落としたいですよね。。

$ git clone https://github.com/bitcoin/bitcoin.git
$ $ tree -L 3 -d
.
└── bitcoin
├── build-aux
│ └── m4
├── build_msvc
│ ├── bench_bitcoin
│ ├── bitcoin-cli
│ ├── bitcoind
│ ├── bitcoin-qt
│ ├── bitcoin-tx
│ ├── bitcoin-util
│ ├── bitcoin-wallet
│ ├── libbitcoin_cli
│ ├── libbitcoin_common
│ ├── libbitcoin_consensus
│ ├── libbitcoin_crypto
│ ├── libbitcoin_node
│ ├── libbitcoin_qt
│ ├── libbitcoin_util
│ ├── libbitcoin_wallet
│ ├── libbitcoin_wallet_tool
│ ├── libbitcoin_zmq
│ ├── libleveldb
│ ├── libminisketch
│ ├── libsecp256k1
│ ├── libtest_util
│ ├── libunivalue
│ ├── msbuild
│ ├── test_bitcoin
│ └── test_bitcoin-qt
├── ci
│ ├── lint
│ ├── retry
│ └── test
├── contrib
│ ├── completions
│ ├── debian
│ ├── devtools
│ ├── guix
│ ├── init
│ ├── linearize
│ ├── macdeploy
│ ├── message-capture
│ ├── qos
│ ├── seeds
│ ├── shell
│ ├── signet
│ ├── testgen
│ ├── tracing
│ ├── verify-binaries
│ ├── verify-commits
│ ├── windeploy
│ └── zmq
├── depends
│ ├── builders
│ ├── hosts
│ ├── packages
│ └── patches
├── doc
│ ├── design
│ ├── man
│ ├── policy
│ └── release-notes
├── share
│ ├── examples
│ ├── pixmaps
│ ├── qt
│ └── rpcauth
├── src
│ ├── bench
│ ├── common
│ ├── compat
│ ├── config
│ ├── consensus
│ ├── crc32c
│ ├── crypto
│ ├── index
│ ├── init
│ ├── interfaces
│ ├── ipc
│ ├── kernel
│ ├── leveldb
│ ├── logging
│ ├── minisketch
│ ├── node
│ ├── policy
│ ├── primitives
│ ├── qt
│ ├── rpc
│ ├── script
│ ├── secp256k1
│ ├── support
│ ├── test
│ ├── univalue
│ ├── util
│ ├── wallet
│ └── zmq
└── test
├── functional
├── fuzz
├── lint
├── sanitizer_suppressions
└── util

各ディレクトリ、各機能ごとの役割を細く見て行くことが必要ですね。

[C言語] 疑似乱数

rand()は 0 から RAND_MAXまでの疑似乱数を返す。stdlib.hに定義されている。
多くのプログラムはエポックからの経過秒数を種にして使用している。

#include <stdio.h>
#include <stdlib.h>

int main() {
    int i;
    printf("RAND_MAX: %u\n", RAND_MAX);
    srand(time(0));

    printf("0からRAND_MAXまでの乱数値\n");
    for(i=0; i< 8; i++)
        printf("%d\n", rand());
    printf("0から20までの乱数値\n");
    for(i=0; i< 8; i++)
        printf("%d\n", (rand()%20)+1);
    return 0;
}

$ ./a.out
RAND_MAX: 2147483647
0からRAND_MAXまでの乱数値
1059493860
583633074
1632571078
678819775
1658879329
1703267400
1565774963
996314262
0から20までの乱数値
13
4
2
13
13
7
11
18

[C言語] 関数のポインタ

#include <stdio.h>

int func_one() {
    printf("これは1つ目の関数です。\n");
    return 1;
}

int func_two() {
    printf("これは2つ目の関数です。\n");
    return 2;
}

int main() {
    int value;
    int (*function_ptr)();

    function_ptr = func_one;
    printf("function_ptr: 0x%08x\n", function_ptr);
    value = function_ptr();
    printf("戻り値: %d\n", value);

    function_ptr = func_two;
    printf("function_ptr: 0x%08x\n", function_ptr);
    value = function_ptr();
    printf("戻り値: %d\n", value);

    return 0;
}

$ ./a.out
function_ptr: 0xcdc907d4
これは1つ目の関数です。
戻り値: 1
function_ptr: 0xcdc907f4
これは2つ目の関数です。
戻り値: 2

[C言語] 構造体

time.hのtm構造体を使用する

#include <stdio.h>
#include <time.h>

int main() {
    long int seconds_since_epoch;
    struct tm current_time, *time_ptr;
    int hour, minute, second, day, month, year;

    seconds_since_epoch = time(0);
    printf("time() - エポックからの通算秒数: %ld\n", seconds_since_epoch);

    time_ptr = &current_time;

    localtime_r(&seconds_since_epoch, time_ptr);

    hour = current_time.tm_hour;
    minute = time_ptr->tm_min;
    second = *((int *) time_ptr);

    printf("現在の時間は: %02d:%02d:%02d\n", hour, minute, second);

    return 0;
}

$ ./a.out
time() – エポックからの通算秒数: 1707729486
現在の時間は: 03:18:06
$ ./a.out
time() – エポックからの通算秒数: 1707729492
現在の時間は: 03:18:12

#include <stdio.h>
#include <time.h>

void dump_time_struct_bytes(struct tm *time_ptr, int size){
    int i;
    unsigned char *raw_ptr;

    printf("0x%08x にある構造体の内容\n", time_ptr);
    raw_ptr = (unsigned char *) time_ptr;
    for(i=0; i<size; i++){
        printf("%02x ", raw_ptr[i]);
        if(i%16 == 15)
            printf("\n");
    }
    printf("\n");
}

int main() {
    long int seconds_since_epoch;
    struct tm current_time, *time_ptr;
    int hour, minute, second, i, *int_ptr;

    seconds_since_epoch = time(0);
    printf("time() - エポックからの通算秒数: %ld\n", seconds_since_epoch);

    time_ptr = &current_time;

    localtime_r(&seconds_since_epoch, time_ptr);

    hour = current_time.tm_hour;
    minute = time_ptr->tm_min;
    second = *((int *) time_ptr);

    printf("現在の時間は: %02d:%02d:%02d\n", hour, minute, second);

    dump_time_struct_bytes(time_ptr, sizeof(struct tm));

    minute = hour = 0;
    int_ptr = (int *) time_ptr;

    for(i=0; i < 3; i++) {
        printf("int ptr @ 0x08x : %d\n", int_ptr, *int_ptr);
        int_ptr++;
    }

    return 0;
}

$ ./a.out
time() – エポックからの通算秒数: 1707730079
現在の時間は: 03:27:59
0xf089a030 にある構造体の内容
3b 00 00 00 1b 00 00 00 03 00 00 00 0c 00 00 00
01 00 00 00 7c 00 00 00 01 00 00 00 2a 00 00 00
00 00 00 00 ff ff 00 00 a0 ab ff ff ff ff ff ff
00 a9 5d d4 aa aa 00 00
int ptr @ 0x08x : -259416016
int ptr @ 0x08x : -259416012
int ptr @ 0x08x : -259416008

[C言語] ユーザID

全てのユーザにはuidという個別の数値が割り当てられる

$ id root
uid=0(root) gid=0(root) groups=0(root)
$ id vagrant
uid=1000(vagrant) gid=1000(vagrant) groups=1000(vagrant),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),110(lxd)

hacking.h

void fatal(char *message) {
    char error_message[100];

    strcpy(error_message, "[!!]致命的なエラー:");
    strncat(error_message, message, 83);
    perror(error_message);
    exit(-1);
}

void *ec_malloc(unsigned int size) {
    void *ptr;
    ptr = malloc(size);
    if(ptr == NULL)
        fatal("ec_malloc()内でメモリ割り当てに失敗しました。");
    return ptr;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "hacking.h"

void usage(char *prog_name, char *filename){
    printf("使用方法: %s <%sに追加するデータ>\n", prog_name, filename);
    exit(0);
}

void fatal(char *);
void *ec_malloc(unsigned int);

int main(int argc, char *argv[]) {
    int userid, fd;
    char *buffer, *datafile;

    buffer = (char *) ec_malloc(100);
    datafile = (char *) ec_malloc(20);
    strcpy(datafile, "./notes");

    if(argc < 2)
        usage(argv[0], datafile);

    strcpy(buffer, argv[1]);

    printf("[DEBUG] buffer @ %p: \'%s\'\n", buffer, buffer);
    printf("[DEBUG] datafile @ %p: \'%s\'\n", datafile, datafile);

    fd = open(datafile, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR);
    if(fd == -1)
        fatal("main()内、ファイルのオープン中にエラーが発生しました。");
    printf("[DEBUG] ファイル記述子]:%d\n", fd);

    userid = getuid();

    if(write(fd, &userid, 4) == -1)
        fatal("main()内、ファイルへのユーザIDの書き込みでエラーが発生しました。");
    write(fd, "\n", 1);

    if(write(fd, buffer, strlen(buffer)) == -1)
        fatal("main()内、ファイルへのバッファの書き込みでエラーが発生しました。");
    write(fd, "\n", 1);

    if(close(fd) == -1)
        fatal("main()内、ファイルのクローズ中にエラーが発生しました。");

    printf("メモが保存されました。\n");
    free(buffer);
    free(datafile);

    return 0;
}

$ gcc -o main main.c
$ ls -l ./main
-rwxrwxr-x 1 vagrant vagrant 13664 Feb 12 02:26 ./main

$ sudo chown root:root ./main
$ sudo chmod u+s ./main
$ ls -l ./main
-rwsrwxr-x 1 root root 13664 Feb 12 02:26 ./main

$ ./main “this is a test of multiuser notes”
[DEBUG] buffer @ 0xaaaaf83ba2a0: ‘this is a test of multiuser notes’
[DEBUG] datafile @ 0xaaaaf83ba310: ‘./notes’
[DEBUG] ファイル記述子]:3
メモが保存されました。
$ ls -l ./notes
-rw——- 1 root vagrant 39 Feb 12 02:31 ./notes
$ sudo cat ./notes

this is a test of multiuser notes
$ sudo hexdump -C ./notes
00000000 e8 03 00 00 0a 74 68 69 73 20 69 73 20 61 20 74 |…..this is a t|
00000010 65 73 74 20 6f 66 20 6d 75 6c 74 69 75 73 65 72 |est of multiuser|
00000020 20 6e 6f 74 65 73 0a | notes.|

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "hacking.h"
#define FILENAME "./notes"

int print_notes(int, int, char *);
int find_user_note(int, int);
int search_note(char *, char *);
void fatal(char *);

int main(int argc, char *argv[]) {
    int userid, printing=1, fd;
    char searchstring[100];

    if(argc > 1)
        strcpy(searchstring, argv[1]);
    else
        searchstring[0] = 0;

    userid = getuid();
    fd = open(FILENAME, O_RDONLY);
    if(fd == -1)
        fatal("main()内、ファイルの読み込みオープンでエラーが発生しました。");

    while(printing)
        printing = print_notes(fd, userid, searchstring);
    printf("-----[ メモの終わり ]------\n");
    close(fd);    

    return 0;
}

int print_notes(int fd, int uid, char *searchstring) {
    int note_length;
    char byte=0, note_buffer[100];

    note_length = find_user_note(fd, uid);
    if(note_length == -1)
        return 0;

    read(fd, note_buffer, note_length);
    note_buffer[note_length] = 0;

    if(search_note(note_buffer, searchstring))
        printf(note_buffer);
    return 1;
}

int find_user_note(int fd, int user_uid) {
    int note_uid = -1;
    unsigned char byte;
    int length;

    while(note_uid != user_uid){
        if(read(fd, &note_uid, 4) != 4)
            return -1;
        if(read(fd, &byte, 1) != 1)
            return -1;

        byte = length = 0;
        while(byte != '\n'){
            if(read(fd, &byte, 1) != 1)
                return -1;
            length++;
        }
    }
    lseek(fd, length * -1L, SEEK_CUR);

    printf("[DEBUG] uid %dの%dバイトのメモを見つけました\n", note_uid, length);
    return length;
}

int search_note(char *note, char *keyword){
    int i, keyword_length, match=0;

    keyword_length = strlen(keyword);
    if(keyword_length == 0)
        return 1;

    for(i=0; i<strlen(note); i++){
        if(note[i] == keyword[match])
            match++;
        else {
            if(note[i] == keyword[0])
                match = 1;
            else
                match = 0;
        }
        if(match == keyword_length)
            return 1;
    }
    return 0;
}

$ ./main
[DEBUG] uid 1000の34バイトのメモを見つけました
this is a test of multiuser notes
—–[ メモの終わり ]——