-
Notifications
You must be signed in to change notification settings - Fork 128
feat: update the Cloudflare quide #1223
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
niusia-ua
wants to merge
10
commits into
main
Choose a base branch
from
updated-cloudflare-quide
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
1f5341f
use global env
niusia-ua 136a358
simplify the guide
niusia-ua 03a32be
remove useless comments in code examples
niusia-ua 2e7170c
fix fmt
niusia-ua 6b90b43
remove code block highlight
niusia-ua 1decf04
Merge branch 'main' into updated-cloudflare-quide
LWJerri 5602513
Merge branch 'main' into updated-cloudflare-quide
LWJerri df23c4d
Merge branch 'main' into updated-cloudflare-quide
LWJerri b2e4b84
Merge branch 'main' into updated-cloudflare-quide
LWJerri 89c66df
Merge branch 'main' into updated-cloudflare-quide
LWJerri File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -23,233 +23,56 @@ If you're looking for the Deno version, please check out [this tutorial](./cloud | |||||
|
|
||||||
| ## Setting Things Up | ||||||
|
|
||||||
| First, create a new project: | ||||||
| First, [create a new project](https://developers.cloudflare.com/workers/get-started/guide/#1-create-a-new-worker-project): | ||||||
|
|
||||||
| ```sh | ||||||
| npm create cloudflare@latest | ||||||
| ``` | ||||||
|
|
||||||
| Then, you will be asked to enter the name of the worker: | ||||||
|
|
||||||
| ```ansi{6} | ||||||
| using create-cloudflare version 2.17.1 | ||||||
|
|
||||||
| ╭ Create an application with Cloudflare Step 1 of 3 | ||||||
| │ | ||||||
| ╰ In which directory do you want to create your application? also used as application name // [!code focus] | ||||||
| ./grammybot // [!code focus] | ||||||
| ``` | ||||||
|
|
||||||
| Here we create a project named `grammybot`, you can choose your own, this will be the name of your worker as well as a part of the request URL. | ||||||
|
|
||||||
| ::: tip | ||||||
| You can change the name of your worker in `wrangler.toml` later. | ||||||
| ::: | ||||||
|
|
||||||
| Next, you will be asked to select the type of your worker, here we choose `"Hello World" Worker`: | ||||||
|
|
||||||
| ```ansi{8} | ||||||
| using create-cloudflare version 2.17.1 | ||||||
|
|
||||||
| ╭ Create an application with Cloudflare Step 1 of 3 | ||||||
| │ | ||||||
| ├ In which directory do you want to create your application? | ||||||
| │ dir ./grammybot | ||||||
| │ | ||||||
| ╰ What type of application do you want to create? // [!code focus] | ||||||
| ● "Hello World" Worker // [!code focus] | ||||||
| ○ "Hello World" Worker (Python) // [!code focus] | ||||||
| ○ "Hello World" Durable Object // [!code focus] | ||||||
| ○ Website or web app // [!code focus] | ||||||
| ○ Example router & proxy Worker // [!code focus] | ||||||
| ○ Scheduled Worker (Cron Trigger) // [!code focus] | ||||||
| ○ Queue consumer & producer Worker // [!code focus] | ||||||
| ○ API starter (OpenAPI compliant) // [!code focus] | ||||||
| ○ Worker built from a template hosted in a git repository // [!code focus] | ||||||
| ``` | ||||||
|
|
||||||
| Next, you will be asked to choose whether you want to use TypeScript, if you want to use JavaScript, choose `No`. | ||||||
| Here we choose `Yes`: | ||||||
|
|
||||||
| ```ansi{11} | ||||||
| using create-cloudflare version 2.17.1 | ||||||
|
|
||||||
| ╭ Create an application with Cloudflare Step 1 of 3 | ||||||
| │ | ||||||
| ├ In which directory do you want to create your application? | ||||||
| │ dir ./grammybot | ||||||
| │ | ||||||
| ├ What type of application do you want to create? | ||||||
| │ type "Hello World" Worker | ||||||
| │ | ||||||
| ╰ Do you want to use TypeScript? // [!code focus] | ||||||
| Yes / No // [!code focus] | ||||||
| ``` | ||||||
|
|
||||||
| Your project will be set up in a few minutes. | ||||||
| After that, you will be asked whether you want to use git for version control, choose `Yes` if you want the repo to be initialized automatically or `No` if you want to initialize it by yourself later. | ||||||
|
|
||||||
| Here we choose `Yes`: | ||||||
|
|
||||||
| ```ansi{36} | ||||||
| using create-cloudflare version 2.17.1 | ||||||
|
|
||||||
| ╭ Create an application with Cloudflare Step 1 of 3 | ||||||
| │ | ||||||
| ├ In which directory do you want to create your application? | ||||||
| │ dir ./grammybot | ||||||
| │ | ||||||
| ├ What type of application do you want to create? | ||||||
| │ type "Hello World" Worker | ||||||
| │ | ||||||
| ├ Do you want to use TypeScript? | ||||||
| │ yes typescript | ||||||
| │ | ||||||
| ├ Copying template files | ||||||
| │ files copied to project directory | ||||||
| │ | ||||||
| ├ Updating name in `package.json` | ||||||
| │ updated `package.json` | ||||||
| │ | ||||||
| ├ Installing dependencies | ||||||
| │ installed via `npm install` | ||||||
| │ | ||||||
| ╰ Application created | ||||||
|
|
||||||
| ╭ Configuring your application for Cloudflare Step 2 of 3 | ||||||
| │ | ||||||
| ├ Installing @cloudflare/workers-types | ||||||
| │ installed via npm | ||||||
| │ | ||||||
| ├ Adding latest types to `tsconfig.json` | ||||||
| │ added @cloudflare/workers-types/2023-07-01 | ||||||
| │ | ||||||
| ├ Retrieving current workerd compatibility date | ||||||
| │ compatibility date 2024-04-05 | ||||||
| │ | ||||||
| ╰ Do you want to use git for version control? // [!code focus] | ||||||
| Yes / No // [!code focus] | ||||||
| ``` | ||||||
|
|
||||||
| Finally, you will be asked whether you want to deploy your worker, choose `No`, since we are going to deploy it when we have a working Telegram bot: | ||||||
|
|
||||||
| ```ansi{49} | ||||||
| using create-cloudflare version 2.17.1 | ||||||
|
|
||||||
| ╭ Create an application with Cloudflare Step 1 of 3 | ||||||
| │ | ||||||
| ├ In which directory do you want to create your application? | ||||||
| │ dir ./grammybot | ||||||
| │ | ||||||
| ├ What type of application do you want to create? | ||||||
| │ type "Hello World" Worker | ||||||
| │ | ||||||
| ├ Do you want to use TypeScript? | ||||||
| │ yes typescript | ||||||
| │ | ||||||
| ├ Copying template files | ||||||
| │ files copied to project directory | ||||||
| │ | ||||||
| ├ Updating name in `package.json` | ||||||
| │ updated `package.json` | ||||||
| │ | ||||||
| ├ Installing dependencies | ||||||
| │ installed via `npm install` | ||||||
| │ | ||||||
| ╰ Application created | ||||||
|
|
||||||
| ╭ Configuring your application for Cloudflare Step 2 of 3 | ||||||
| │ | ||||||
| ├ Installing @cloudflare/workers-types | ||||||
| │ installed via npm | ||||||
| │ | ||||||
| ├ Adding latest types to `tsconfig.json` | ||||||
| │ added @cloudflare/workers-types/2023-07-01 | ||||||
| │ | ||||||
| ├ Retrieving current workerd compatibility date | ||||||
| │ compatibility date 2024-04-05 | ||||||
| │ | ||||||
| ├ Do you want to use git for version control? | ||||||
| │ yes git | ||||||
| │ | ||||||
| ├ Initializing git repo | ||||||
| │ initialized git | ||||||
| │ | ||||||
| ├ Committing new files | ||||||
| │ git commit | ||||||
| │ | ||||||
| ╰ Application configured | ||||||
|
|
||||||
| ╭ Deploy with Cloudflare Step 3 of 3 | ||||||
| │ | ||||||
| ╰ Do you want to deploy your application? // [!code focus] | ||||||
| Yes / No // [!code focus] | ||||||
| ``` | ||||||
| Follow the instructions to set up the project. | ||||||
| In this guide, we assume that you start the project with the `Hello World` example in TypeScript. | ||||||
| The rest of the options are on your own. | ||||||
|
|
||||||
| ## Install Dependencies | ||||||
|
|
||||||
| `cd` into `grammybot` (replace this by your worker's name you set above), install `grammy`, and other packages you might need: | ||||||
| `cd` into your project directory, install `grammy`, and other packages you might need: | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
|
||||||
| ```sh | ||||||
| npm install grammy | ||||||
| ``` | ||||||
|
|
||||||
| ## Creating Your Bot | ||||||
|
|
||||||
| Edit `src/index.js` or `src/index.ts`, and write this code inside: | ||||||
|
|
||||||
| ```ts{11,28-29,38,40-42,44} | ||||||
| /** | ||||||
| * Welcome to Cloudflare Workers! This is your first worker. | ||||||
| * | ||||||
| * - Run `npm run dev` in your terminal to start a development server | ||||||
| * - Open a browser tab at http://localhost:8787/ to see your worker in action | ||||||
| * - Run `npm run deploy` to publish your worker | ||||||
| * | ||||||
| * Learn more at https://developers.cloudflare.com/workers/ | ||||||
| */ | ||||||
| Edit `src/index.ts`, and write this code inside: | ||||||
|
|
||||||
| ```ts | ||||||
| import { env } from "cloudflare:workers"; | ||||||
| import { Bot, Context, webhookCallback } from "grammy"; | ||||||
|
|
||||||
| export interface Env { | ||||||
| // Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/ | ||||||
| // MY_KV_NAMESPACE: KVNamespace; | ||||||
| // | ||||||
| // Example binding to Durable Object. Learn more at https://developers.cloudflare.com/workers/runtime-apis/durable-objects/ | ||||||
| // MY_DURABLE_OBJECT: DurableObjectNamespace; | ||||||
| // | ||||||
| // Example binding to R2. Learn more at https://developers.cloudflare.com/workers/runtime-apis/r2/ | ||||||
| // MY_BUCKET: R2Bucket; | ||||||
| // | ||||||
| // Example binding to a Service. Learn more at https://developers.cloudflare.com/workers/runtime-apis/service-bindings/ | ||||||
| // MY_SERVICE: Fetcher; | ||||||
| // | ||||||
| // Example binding to a Queue. Learn more at https://developers.cloudflare.com/queues/javascript-apis/ | ||||||
| // MY_QUEUE: Queue; | ||||||
| BOT_INFO: string; | ||||||
| BOT_TOKEN: string; | ||||||
| BOT_INFO: string; | ||||||
| } | ||||||
|
|
||||||
| const bot = new Bot(env.BOT_TOKEN, { botInfo: JSON.parse(env.BOT_INFO) }); | ||||||
| const handleUpdate = webhookCallback(bot, "cloudflare-mod"); | ||||||
|
|
||||||
| bot.command("start", async (ctx: Context) => { | ||||||
| await ctx.reply("Hello, world!"); | ||||||
| }); | ||||||
|
|
||||||
| export default { | ||||||
| async fetch( | ||||||
| request: Request, | ||||||
| env: Env, | ||||||
| ctx: ExecutionContext, | ||||||
| ): Promise<Response> { | ||||||
| const bot = new Bot(env.BOT_TOKEN, { botInfo: JSON.parse(env.BOT_INFO) }); | ||||||
|
|
||||||
| bot.command("start", async (ctx: Context) => { | ||||||
| await ctx.reply("Hello, world!"); | ||||||
| }); | ||||||
|
|
||||||
| return webhookCallback(bot, "cloudflare-mod")(request); | ||||||
| }, | ||||||
| fetch: handleUpdate | ||||||
| }; | ||||||
| ``` | ||||||
|
|
||||||
| Here, we first import `Bot`, `Context` and `webhookCallback` from `grammy`. | ||||||
| Here, we first import `env` from `cloudflare:workers` to access your environment variables and secrets in the global scope. | ||||||
| Then, we import `Bot`, `Context` and `webhookCallback` from `grammy` to set up the bot. | ||||||
|
|
||||||
| Inside the interface `Env`, we add a variable `BOT_INFO`. | ||||||
| This is an environment variable that stores your bot info. | ||||||
| You can get your bot info by calling Telegram Bot API with `getMe` method. | ||||||
|
|
||||||
| Inside the interface `Env`, we add a variable `BOT_INFO`, this is an environment variable that stores your bot info, you can get your bot info by calling Telegram Bot API with `getMe` method. | ||||||
| Open this link in your web browser: | ||||||
|
|
||||||
| ```ansi:no-line-numbers | ||||||
|
|
@@ -275,11 +98,12 @@ If successful, you will see a JSON response similar to this: | |||||
| } | ||||||
| ``` | ||||||
|
|
||||||
| Now, open `wrangler.toml` in the root of your project and add an environment variable `BOT_INFO` under `[vars]` section with the value from `result` object you get above like this: | ||||||
| Store this info as the [secrets](https://developers.cloudflare.com/workers/configuration/secrets/) of your project. | ||||||
| In development, they can be set in the `.dev.vars` file, and in production, via the dashboard. | ||||||
|
|
||||||
| ```toml | ||||||
| [vars] | ||||||
| BOT_INFO = """{ | ||||||
| ```env | ||||||
| BOT_TOKEN= | ||||||
| BOT_INFO='{ | ||||||
| "id": 1234567890, | ||||||
| "is_bot": true, | ||||||
| "first_name": "mybot", | ||||||
|
|
@@ -288,36 +112,9 @@ BOT_INFO = """{ | |||||
| "can_read_all_group_messages": false, | ||||||
| "supports_inline_queries": true, | ||||||
| "can_connect_to_business": false | ||||||
| }""" | ||||||
| ``` | ||||||
|
|
||||||
| Replace the bot info with what you get from the web browser. | ||||||
| Pay attention to the three double quotation marks `"""` at the beginning and end. | ||||||
|
|
||||||
| In addition to `BOT_INFO`, we also add a variable `BOT_TOKEN`, this is an environment variable that stores your bot token that is used to create your bot. | ||||||
|
|
||||||
| You may notice that we just define the variable `BOT_TOKEN`, but didn't assign it yet. | ||||||
| Usually you need to store your environment variable in `wrangler.toml`, however, this is not safe in our case, since the bot token should be kept secret. | ||||||
| Cloudflare Workers provide us a safe way to store sensitive information like API keys and auth tokens in environment variable: [secrets](https://developers.cloudflare.com/workers/configuration/secrets/#secrets-on-deployed-workers)! | ||||||
|
|
||||||
| ::: tip | ||||||
| Secret values are not visible within Wrangler or the Cloudflare dashboard after you define them. | ||||||
| ::: | ||||||
|
|
||||||
| You can add a secret to your project using the following command: | ||||||
|
|
||||||
| ```sh | ||||||
| npx wrangler secret put BOT_TOKEN | ||||||
| }' | ||||||
| ``` | ||||||
|
|
||||||
| Follow the instruction and input your bot token, your bot token will be uploaded and encrypted. | ||||||
|
|
||||||
| ::: tip | ||||||
| You can change to whatever name you want for the environment variables, but keep in mind that you do the same in following steps. | ||||||
| ::: | ||||||
|
|
||||||
| Inside the function `fetch()`, we create a bot with `BOT_TOKEN` which replies "Hello, world!" when it receives `/start`. | ||||||
|
|
||||||
| ## Deploying Your Bot | ||||||
|
|
||||||
| Now, you can deploy your bot using the following command: | ||||||
|
|
@@ -356,28 +153,6 @@ If it responds, it means you're good to go! | |||||
|
|
||||||
| For testing and debugging purposes, you can run a local or remote development server before deploying your bot to production. | ||||||
|
|
||||||
| In a development environment, your bot doesn't have access to your secret environment variables. | ||||||
| So, [according to Cloudflare](https://developers.cloudflare.com/workers/configuration/secrets/#local-development-with-secrets), you can create a `.dev.vars` file in the root of your project to define secrets: | ||||||
|
|
||||||
| ```env | ||||||
| BOT_TOKEN=<your_bot_token> # <- replace this with your bot token. | ||||||
| ``` | ||||||
|
|
||||||
| Don't forget to add `BOT_INFO` for development as well. | ||||||
| Click [here](https://developers.cloudflare.com/workers/configuration/environment-variables/) and [here](https://developers.cloudflare.com/workers/configuration/secrets/) for more details about environment variables and secrets. | ||||||
|
|
||||||
| Replace `BOT_INFO` and `BOT_TOKEN` with your value if you change the environment variable name in the previous step. | ||||||
|
|
||||||
| ::: tip | ||||||
| You can use a different bot token for development to ensure it doesn't affect production. | ||||||
| ::: | ||||||
|
|
||||||
| Now, you can run the following command to start a development server: | ||||||
|
|
||||||
| ```sh | ||||||
| npm run dev | ||||||
| ``` | ||||||
|
|
||||||
| Once the development server has started, you can test your bot by sending sample updates to it using tools like `curl`, [Insomnia](https://insomnia.rest), or [Postman](https://postman.com). | ||||||
| Refer to [here](https://core.telegram.org/bots/webhooks#testing-your-bot-with-updates) for update examples and [here](https://core.telegram.org/bots/api#update) for more information on the update structure. | ||||||
|
|
||||||
|
|
||||||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The rest of what options?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.