Flutter即时通讯插件chatterbox的使用

发布于 1周前 作者 yuanlaile 来自 Flutter

Flutter即时通讯插件chatterbox的使用

Chatterbox 是一个用于构建多层次Telegram机器人对话流程的简单框架。它基于 televerse 库。

功能

允许处理用户发送的不同类型的消息,并在给定的上下文中回复这些消息。

开始使用

可以同时使用webhook和轮询方式。

使用方法

使用webhook和云函数
@CloudFunction()
Future<Response> function(Map<String, dynamic> updateJson) async {
  try {
    final flows = <Flow>[
      // todo
    ];

    Chatterbox(Config.botToken, flows, StoreProxy()).invokeFromWebhook(updateJson);
    return Response.ok(
      null,
      headers: {'Content-Type': 'application/json'},
    );
  } catch (error) {
    return Response.badRequest();
  }
}

编写对话流程

创建对话流程
响应用户输入

ReactionResponse 是一个简单的反应,允许响应用户的输入。

ReactionResponse(
  /// 必需的文本消息以回复用户
  text: '你最喜欢的数字是多少?',
  /// 可选按钮
  buttons: [
    InlineButton(
      /// 按钮文本
      title: '七十三',
      /// 当按下此按钮时要调用的步骤的URI
      nextStepUri: NextStep.toStepUri().appendArgs('73')
    ),
  ],
);

它还可以包含按钮。

在Google Cloud Run上设置

  1. 安装gcloud控制台实用程序。
  2. 运行 gcloud init
  3. 创建一个项目并为其分配一个唯一ID,或者在 Google Cloud Console 中创建一个项目。
  4. 转到Google Cloud Run并执行以下操作:
  5. 启用身份和访问管理(IAM)API。
  6. 触发构建。
  7. 添加密钥。

由于示例代码中未包含具体的示例代码,这里提供一个完整的示例来演示如何使用 chatterbox 插件:

import 'package:chatterbox/chatterbox.dart';
import 'package:televerse/televerse.dart';

void main() async {
  // 初始化配置
  final config = Config(botToken: 'YOUR_BOT_TOKEN');

  // 创建对话流
  final flows = <Flow>[
    Flow(
      name: 'start',
      steps: [
        Step(
          name: 'welcome',
          action: (context) async {
            return ReactionResponse(
              text: '欢迎来到聊天机器人!\n你最喜欢的数字是多少?',
              buttons: [
                InlineButton(
                  title: '七十三',
                  nextStepUri: NextStep.toStepUri().appendArgs('73')
                ),
              ],
            );
          },
        ),
        Step(
          name: 'favoriteNumber',
          action: (context) async {
            final args = context.arguments;
            final number = args['number'];
            return ReactionResponse(
              text: '你的最爱数字是 $number!',
            );
          },
        ),
      ],
    ),
  ];

  // 创建Chatterbox实例
  final chatterbox = Chatterbox(config, flows, StoreProxy());

  // 模拟用户输入
  final updateJson = {
    "update_id": 123456,
    "message": {
      "message_id": 123,
      "from": {"id": 123456, "is_bot": false, "first_name": "John", "last_name": "Doe", "username": "johndoe"},
      "chat": {"id": 123456, "first_name": "John", "last_name": "Doe", "username": "johndoe", "type": "private"},
      "date": 1689900000,
      "text": "七十三",
    },
  };

  // 处理用户输入
  await chatterbox.invokeFromWebhook(updateJson);

  print('处理完成');
}

更多关于Flutter即时通讯插件chatterbox的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter即时通讯插件chatterbox的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中集成和使用ChatterBox即时通讯插件的示例代码。ChatterBox是一个用于构建即时通讯功能的Flutter插件,它提供了实时消息传递的能力。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加ChatterBox的依赖:

dependencies:
  flutter:
    sdk: flutter
  chatterbox: ^最新版本号  # 请替换为实际的最新版本号

然后运行flutter pub get来获取依赖。

2. 配置权限

由于即时通讯通常需要网络权限,你需要在AndroidManifest.xml(对于Android)和Info.plist(对于iOS)中添加必要的权限。

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

3. 初始化ChatterBox

在你的Flutter项目的入口文件(通常是main.dart)中初始化ChatterBox:

import 'package:flutter/material.dart';
import 'package:chatterbox/chatterbox.dart';

void main() {
  // 初始化ChatterBox
  ChatterBox.initialize(
    apiKey: "你的API密钥",  // 替换为你的ChatterBox API密钥
    userId: "用户ID",       // 替换为当前用户的唯一标识符
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChatScreen(),
    );
  }
}

4. 实现聊天界面

创建一个简单的聊天界面,包括发送和接收消息的功能。

import 'package:flutter/material.dart';
import 'package:chatterbox/chatterbox.dart';

class ChatScreen extends StatefulWidget {
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final TextEditingController _messageController = TextEditingController();
  final List<String> _messages = [];

  @override
  void initState() {
    super.initState();

    // 监听新消息
    ChatterBox.onMessageReceived.listen((message) {
      setState(() {
        _messages.add(message.text);
      });
    });
  }

  void _sendMessage() {
    final String messageText = _messageController.text;
    if (messageText.isNotEmpty) {
      ChatterBox.sendMessage(messageText);
      setState(() {
        _messages.add(messageText);
        _messageController.clear();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Chat Screen'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: <Widget>[
            Expanded(
              child: ListView.builder(
                itemCount: _messages.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(_messages[index]),
                  );
                },
              ),
            ),
            Divider(),
            TextField(
              controller: _messageController,
              decoration: InputDecoration(border: OutlineInputBorder()),
              onSubmitted: _sendMessage,
            ),
            SizedBox(height: 8.0),
            Button(
              onPressed: _sendMessage,
              child: Text('Send'),
            ),
          ],
        ),
      ),
    );
  }
}

5. 处理连接状态

你可以通过监听ChatterBox的连接状态来显示相应的UI(例如,显示“连接中”或“断开连接”的提示)。

@override
void initState() {
  super.initState();

  // 监听连接状态
  ChatterBox.onConnectionStateChanged.listen((state) {
    print("Connection state changed: $state");
    // 更新UI来反映连接状态
  });

  // 监听新消息
  ChatterBox.onMessageReceived.listen((message) {
    setState(() {
      _messages.add(message.text);
    });
  });
}

6. 处理用户登录和注销

根据你的应用需求,你可能还需要处理用户的登录和注销逻辑。ChatterBox通常会在用户登录时初始化,并在用户注销时重置或销毁连接。

void _loginUser() {
  // 假设这里有一些用户登录的逻辑
  ChatterBox.initialize(
    apiKey: "有一些你的用户API注销密钥的逻辑",

      ChatuserIdter:Box ".登录dispose后的();用户  ID//", 
释放  资源);

}}

void _###logout 总结User () {以上 代码 // 展示了假设这里如何在Flutter项目中集成和使用ChatterBox即时通讯插件。这只是一个基本的示例,实际应用中你可能需要根据具体需求进行更多的定制和扩展。

回到顶部