如何编写Telegram Bot

最近在处理如何把经纬度转换成日本的 MAPCODE 的问题。在外出行的时候,经常使用的设备都是手机,如何在手机上方便的计算旅游景点的 MAPCODE 然后使用车载导航呢? 我的想法是做一个 Telegram Bot,输入景点的 Plus Code (opens new window), 然后返回 MAPCODE。

# 申请 Bot

首先,你要去找 BotFather (opens new window)申请 Bot。 通过简单的对话就可以创建 Bot。使用 /start 命令可以查看所有支持的指令。

输入, /newbot 就可以创建 Bot 了,通过对话模式可以设定 Bot 的名字。然后你可以得到一个属于这个 Bot 的 token,格式类似于 577XXXXX:AAEMUXqXrgRE9R2jPcOXXXXX。 拿到这个 token 就可以构建 Bot 了。

# 构建 Bot API

Bot API 本质是 HTTPS API,通过构建请求来实现功能。不过构造 HTTPS 请求本身很枯燥,已经有很多现成的框架可供我们使用。本人擅长使用 JavaScript,所以选择了 telegraf.js (opens new window) 这个框架。

# Bot 代码示例

import { Telegraf } from 'telegraf';

const bot = new Telegraf(process.env.BOT_TOKEN);

bot.start(ctx => {
  const message = `I can help you to query MAPCODE with Telegram.\nYou can copy plus code from Google Maps and paste it to tell me.`;
  ctx.reply(message);
});

bot.help(ctx => {
  ctx.replyWithMarkdownV2(
    'Send me a [plus code](https://maps.google.com/pluscodes/)'
  );
  ctx.reply(`MapDoge Version ${process.env.npm_package_version}`);
});

bot.launch();

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

Telegram Bot 默认都支持 /start/help 命令。所以我就贴出了这两个命令的简单写法。使用成熟的框架可以大大简化编写 Bot 的复杂度。

# 总结

Telegram Bot 有完善的文档和生态,编写一个 Bot 并没有想象的那么难。大家都可以尝试下,非常方便实现在手机端的一些自定义功能。

# 参考

Bot Code Examples (opens new window)

mapdoge-bot (opens new window)

使用MobX管理React的状态

使用 PWA 框架进行应用开发,不论是 Vue 还是 React,最关注的设计应该就是状态的管理了。React 生态下状态管理的框架可谓是五花八门,本人目前用过两个,分别是 @reduxjs/toolkit (opens new window)mobx-react (opens new window)。 个人感觉 Mobx 用起来更简洁,所以本文着重介绍 Mobx。

# 安装 MobX

MobX 本来就可以独立 PWA 框架来使用,所以安装的时候需要安装本体和 React 集成库。

pnpm install mobx-react-lite mobx
1

# 设计 Store

为了测试 MobX 的使用,我写了一个简单的 Todo 例子,接下来讲解如何设计 Store 方便使用。

export class TodoList {
  @observable.shallow list: TodoItem[] = [];

  constructor() {
    makeObservable(this);
  }

  @action
  private fromJS = () => {
    this.list = this.list.map(
      todo => new TodoItem(todo.title, todo.id, todo.completed)
    );
  };

  @action
  addTodo = (text: string) => {
    this.list.push(new TodoItem(text));
  };

  @action
  removeTodo = (todo: TodoItem) => {
    this.list.splice(this.list.indexOf(todo), 1);
  };

  @action
  removeCompleted = () => {
    this.list = this.activeTodos;
  };

  @action
  toggleAll = (value: boolean) => {
    this.list.forEach(todo => {
      todo.updateCompleted(value);
    });
  };

  @computed
  get showTodo(): boolean {
    return this.list.length > 0;
  }

  @computed
  get allTodos(): TodoItem[] {
    return this.list;
  }

  @computed
  get completedTodos(): TodoItem[] {
    return this.list.filter(todo => todo.completed);
  }

  @computed
  get activeTodos(): TodoItem[] {
    return this.list.filter(todo => !todo.completed);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

不同于 React Hooks 函数式声明,Mobx 我们推荐使用 Class 方式来声明,通过修饰符来绑定属性和方法对应 MobX 的相关概念。MobX 推荐使用 action 进行数据的更改,使用 computed 完成对数据的筛选和处理。不建议直接更改声明的数据。

# 设计全局 Store

export type RootStore = {
  todoList: TodoList;
};

export const store: RootStore = {
  todoList
};

const StoreContext = React.createContext<RootStore>(store);

export const StoreProvider = StoreContext.Provider;

export const useStore = () => React.useContext(StoreContext);
1
2
3
4
5
6
7
8
9
10
11
12
13

通过声明全局 Store,模块化设计各个子 Store,这里虽然只有一个 todoList, 但可以根据应用规模添加子模块,方便扩展。

# Root 导入 Store

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <StoreProvider value={store}>
      <App />
    </StoreProvider>
  </React.StrictMode>
);
1
2
3
4
5
6
7

在 React 根节点声明 Store, 保证整个应用都可以同步到 store 的数据。

# 封装 View

我们需要在使用 store 的地方,调用 observer 保证状态的更新能及时反应到视图上。

const TodoView = () => {
  const { todoList } = useStore();

  return (
    <section className="todoapp">
      <header className="header">
        <h1>todos</h1>
      </header>
    </section>
  );
};

export default observer(TodoView);
1
2
3
4
5
6
7
8
9
10
11
12
13

# 总结

MobX 的状态更新原理是基于 Proxy (opens new window)。 通过代理声明的数据对象,在读取和写入的时候执行相关回调进行更新。

# 参考

mobx-react-todo (opens new window)

Git 提交规范

良好的代码风格很重要,但是良好的 commit 记录同样重要。我们提交代码的时候都要提交 commit message,否则就不允许提交。

$ git commit -m "hello world"
1

# commit message 格式

目前最流行的提交规范是Conventional Commits (opens new window),格式如下:

<type>[optional scope]: <description>

[optional body]

[optional footer(s)]
1
2
3
4
5

Header 有三个字段,type(必须),scope(可选) 和 description(必须)。

type 用于说明 commit 的类别,有以下几个选项:build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test

build: 对构建系统或者外部依赖项进行了修改
chore: 构建过程或辅助工具的变动
ci: 对CI配置文件或脚本进行了修改
docs: 对文档进行了修改
feat: 增加新功能
fix: 修复BUG
perf: 优化相关,比如提升性能,体验
refactor: 重构代码
revert: 回滚到上一个版本
style: 修改代码格式
test: 添加测试代码
1
2
3
4
5
6
7
8
9
10
11

scope 用于说明 commit 影响的范围,比如某个组件的修改。

description 是 commit 目的的简短描述,不超过 50 个字符。最好以动词开头,首字母小写,末尾不加句号(.)

# Body

Body 是可选的,用来对本次提交进行详细描述, 可以写成多行,例如:

fix: prevent racing of requests

Introduce a request id and a reference to latest request. Dismiss
incoming responses other than from latest request.
1
2
3
4

Footer 也是可选的,主要有两个使用情况。一种是不兼容性更新:

chore!: drop support for Node 6

BREAKING CHANGE: use JavaScript features not available in Node 6.
1
2
3

一种是引用提交的问题,例如本次提交是修正某个 Issue 的问题。

feat(lang): add Polish language

Closes #234
1
2
3

# 总结

良好的 commit 提交规范和代码规范同样重要。

# 参考

Commit message 和 Change log 编写指南 (opens new window)