前往
大廳
主題

OpenAI to Line Bot

冰峰Will | 2022-12-14 10:13:53 | 巴幣 2 | 人氣 416


我而外加了AI生成圖片的指令(指令為: ![敘述])
注意:
OpenAI 只能適用三個月,給予$18 的免費使用量。

我使用Node.js開發,我就只提供我的app.js拉

require('dotenv').config();

const line = require('@line/bot-sdk');
const express = require('express');
const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
    apiKey: process.env.OPENAI_API_KEY,
  });
  const openai = new OpenAIApi(configuration);
  

// create LINE SDK config from env variables
const config = {
  channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
  channelSecret: process.env.CHANNEL_SECRET,
};

// create LINE SDK client
const client = new line.Client(config);

// create Express app
// about Express itself: https://expressjs.com/
const app = express();

// register a webhook handler with middleware
// about the middleware, please refer to doc
app.post('/callback', line.middleware(config), (req, res) => {
  Promise
    .all(req.body.events.map(handleEvent))
    .then((result) => res.json(result))
    .catch((err) => {
      console.error(err);
      res.status(500).end();
    });
});


// event handler
async function handleEvent(event) {
    if (event.type !== 'message' || event.message.type !== 'text') {
      // ignore non-text-message event
      return Promise.resolve(null);
    }
    let echo;
    if(event.message.text[0] === "!"){
        const response = await openai.createImage({
            prompt: event.message.text.substr(1),
            n: 1,
            size: "1024x1024",
        });
        const image_url = response.data.data[0].url;
        echo = {
            type: 'image',
            originalContentUrl: image_url,
            previewImageUrl: image_url
       };
    }else{
        const completion = await openai.createCompletion({
            model: "text-davinci-003",
            prompt: event.message.text ,
            max_tokens: 256,
        });
        echo = { type: 'text', text: completion.data.choices[0].text.trim() };
    }

    
  
    // use reply API
    return client.replyMessage(event.replyToken, echo);
  }

// listen on port
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`listening on ${port}`);
});


順便宣傳DC群
這裡包含了繪畫創作、BOT娛樂、遊戲討論、影像分享、程式交流等內容。

創作回應

更多創作