投稿時間:2023-01-03 04:15:26 RSSフィード2023-01-03 04:00 分まとめ(19件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
海外TECH DEV Community How to Build a Telegram Bot using Typescript & Node.js https://dev.to/eludadev/how-to-build-a-telegram-bot-using-typescript-nodejs-3j5e How to Build a Telegram Bot using Typescript amp Node js IntroductionIn this tutorial you ll learn all the steps that go into building a dead simple Telegram bot and hosting it on the cloud It will greet people and apply FANCY text effects You ll be writing code using the Typescript language and running it on the Node js server environment And seeing as Telegram bots are built on an HTTP based API you ll be using the GrammY framework for higher level abstractions and a better programming experience PrerequisitesBefore writing any code make sure to have the following programs installed on your computer Telegram client Node js v NPM v and cURL VS Code or any other IDE of choice You ll be using Cyclic to host this project on the cloud so make sure to sign up referral link and take advantage of the Free Forever tier And while you don t have to be an expert in it you should know a bit of Typescript You ll be using it to write all the code in this tutorial Setup the Project Downloading the starter filesStart up this project by cloning the final version into your computer git clone cd telegram botAnd make sure to roll it back to its very first stage so you can learn how to build the rest of it in this tutorial git reset hard eaaeedabdcbcfddaAfter that s done install the project s dependencies npm install Getting your Telegram bot API tokenUsing the Telegram client start a conversation with the BotFather Send it the following messages newbotYour bot name Your bot username can t contain spaces and must end in “bot After that create a new file in the project s root directory called env Paste the following line into that file replacing lt YOUR API TOKEN gt with your bot s API token that you just got from the last message with BotFather TELEGRAM TOKEN lt YOUR API TOKEN gt Initializing the Telegram botCreate a new file called bot ts in the src directory That s where you ll be writing code for the rest of this tutorial You ll be using the GrammY framework to build this bot it s much easier this way instead of interacting directly with the API routes Head into the bot script and import the library in question import Bot from grammy Create a bot using the Telegram tokenconst bot new Bot process env TELEGRAM TOKEN As you can see the bot is created with the TELEGRAM TOKEN variable that you just set in the env file After that handle all message events by responding with a friendly robot introduction const introductionMessage Hello I m a Telegram bot I m powered by Cyclic the next generation serverless computing platform lt b gt Commands lt b gt yo Be greeted by me effect text Show a keyboard to apply text effects to text const replyWithIntro ctx any gt ctx reply introductionMessage parse mode HTML bot on message replyWithIntro Take note of the parse mode parameter It s used to allow HTML tags in the message response such as lt b gt Commands lt b gt And finally start up the bot by running one method bot start Follow that by executing the bot script npm run devAnd boom You ve got yourself a dead simple bot running on your computer You can test it out by sending it a message on Telegram you may want to follow the link previously given to you by BotFather Handle Basic CommandsTelegram bots can handle commands which aren t much different from ordinary messages The syntax for such interactions follows the following format bot command start replyWithIntro Test it out by sending the start message to your bot Note that your program is automatically updated once you modify the bot script After that s done modify your bot to handle the yo command It will simply respond with the username of the sender Handle the yo command to greet the userbot command yo ctx gt ctx reply Yo ctx from username And since the bot on “message event handler is on top it will catch all messages and the start and yo commands won t have an effect Please make sure to always keep it at the bottom of the file Keep this at the bottom of the filebot on message replyWithIntro Build Inline KeyboardsTelegram bots can also respond with a set of buttons underneath the message Let s do a simple demonstration Change the introductory response to also contain a button that links users to the Cyclic website the platform that we ll use to deploy our bot to the cloud for free at the end of this tutorial import InlineKeyboard from grammy const aboutUrlKeyboard new InlineKeyboard url Host your own bot for free const replyWithIntro ctx any gt ctx reply introductionMessage reply markup aboutUrlKeyboard parse mode HTML After this step you may want to re execute the bot script after interrupting it with the Ctrl C keyboard combination npm run dev A more advanced exampleLet s now do a more advanced example Other inline keyboards may contain general buttons whose actions can be handled to the furthest extent Handle the effectcommand and make it apply bold italic and a bunch more effects to text import chunk from lodash import applyTextEffect Variant from textEffects import type Variant as TextEffectVariant from textEffects type Effect code TextEffectVariant label string const allEffects Effect code w label Monospace code b label Bold code i label Italic code d label Doublestruck code o label Circled code q label Squared const effectCallbackCodeAccessor effectCode TextEffectVariant gt effect effectCode const effectsKeyboardAccessor effectCodes string gt const effectsAccessor effectCodes string gt effectCodes map code gt allEffects find effect gt effect code code const effects effectsAccessor effectCodes const keyboard new InlineKeyboard const chunkedEffects chunk effects for const effectsChunk of chunkedEffects for const effect of effectsChunk effect amp amp keyboard text effect label effectCallbackCodeAccessor effect code keyboard row return keyboard const textEffectResponseAccessor originalText string modifiedText string gt Original originalText modifiedText nModified modifiedText const parseTextEffectResponse response string originalText string modifiedText string gt const originalText response match Original as any const modifiedTextMatch response match Modified let modifiedText if modifiedTextMatch modifiedText modifiedTextMatch if modifiedTextMatch return originalText else return originalText modifiedText Handle the effect command to apply text effects using an inline keyboardbot command effect ctx gt ctx reply textEffectResponseAccessor ctx match reply markup effectsKeyboardAccessor allEffects map effect gt effect code Handle text effects from the effect keyboardfor const effect of allEffects const allEffectCodes allEffects map effect gt effect code bot callbackQuery effectCallbackCodeAccessor effect code async ctx gt const originalText parseTextEffectResponse ctx msg text const modifiedText applyTextEffect originalText effect code la await ctx editMessageText textEffectResponseAccessor originalText modifiedText reply markup effectsKeyboardAccessor allEffectCodes filter code gt code effect code Handle Inline QueriesTelegram bots support inline queries a feature which enables them to be invoked from any chat within Telegram by calling them with their “ username Let s use this to allow users to apply text effects in any conversation using your bot Enabling inline mode for your Telegram botBy default this feature comes disabled Contact BotFather to enable it mybotsSelect your bot from the inline keyboardBot settingsInline modeTurn on Handling the “effect inline queryInline queries are generally handled by matching a RegEx pattern We ll listen for the “effect effect text query and handle it by applying effect to text const queryRegEx effect monospace bold italic bot inlineQuery queryRegEx async ctx gt const fullQuery ctx inlineQuery query const fullQueryMatch fullQuery match queryRegEx if fullQueryMatch return const effectLabel fullQueryMatch const originalText fullQueryMatch const effectCode allEffects find effect gt effect label toLowerCase effectLabel toLowerCase code const modifiedText applyTextEffect originalText effectCode as Variant await ctx answerInlineQuery type article id text effect title Text Effects input message content message text Original originalText Modified modifiedText parse mode HTML reply markup new InlineKeyboard switchInline Share fullQuery url description Create stylish Unicode text all within Telegram cache time one month in seconds Polish the Telegram BotIt s often useful for Telegram bots to display a list of supported commands and while we re already doing that in the introductory message there s a more formal way of doing so and it s as simple as one command Suggest commands in the menubot api setMyCommands command yo description Be greeted by the bot command effect description Apply text effects on the text usage effect text Note that to see the new menu you must restart your Telegram client Furthermore professional bots come with a profile picture and a well formed description You can do all of that by contacting BotFather Edit botEdit about Edit description Edit botpic Deploy the Telegram Bot to the Cloud Long Polling vs WebhooksThere are two fundamentally different ways of deploying your Telegram bot to the web The first one is Long Polling and we ve already been using it in this tutorial by running bot start With it bots constantly send requests to the Telegram servers checking for new messages and responding to them accordingly This approach is not compatible with the serverless architecture as the latter expects applications to only run once and only on demand “Serverless means applications are only on for the time it takes to process individual requests They are suspended immediately after each response is sent ーCyclic docs The solution to this problem is deployment by Webhooks an alternative strategy that makes the Telegram client itself contact your bot when there s a new message And while this comes with its own drawbacks it s fully compatible with serverless architecture Using Webhooks for deploymentBy following the NODE ENV environment variable we can tell whether the bot instance is running in a development or a production stage Replace the bot start command with the following import webhookCallback from grammy import express from express Start the serverif process env NODE ENV production Use Webhooks for the production server const app express app use express json app use webhookCallback bot express const PORT process env PORT app listen PORT gt console log Bot listening on port PORT else Use Long Polling for development bot start Pushing all files to a Github RepositoryIt s imperative that we use a Github repository to store our bot files so we can deploy it to the cloud After creating a new repository either public or private run the following commands to link it with your local Git instance replacing lt YOUR GH REPO LINK gt with your repo s URL export GH REPO lt YOUR GH REPO LINK gt git remote remove origingit remote add origin GH REPO git After that stage commit and push your files to the new remote origin git add git commit m Build the Telegram bot git branch M maingit push origin main Deploying for free using CyclicAfter creating your Cyclic account referral link use it to deploy your new Telegram bot It s free forever and no credit card is required Note that you must sign up using the same Github account that you used to create your bot s repository Open your Cyclic dashboard click on the Deploy button and switch to the “Link your own tab Search for your bot s repo and click on the “Connect button Then sit back and watch it do all the work for you The final step is setting the same environment variables as you did in the env file Open your Cyclic deployment s dashboard page switch to the Variables page and set the appropriate values for the environment variables NODE ENV productionTELEGRAM TOKEN your bot s API token same as env file Connecting your Telegram bot to your Cyclic serverYou want to tell Telegram to send the Webhook requests to your Cyclic server So conclude this project by copying your Cyclic deployment s URL and running these commands export TELEGRAM API TOKEN YOUR TELEGRAM API TOKENexport TELEGRAM WEBHOOK URL YOUR CYCLIC DEPLOYMENT URLcurl TELEGRAM API TOKEN setWebhook url TELEGRAM WEBHOOK URL And boom Your bot s now actively running on the cloud You may stop your local development instance by pressing Ctrl C and notice how your bot is still working ConclusionYou ve successfully reached the end of this tutorial There are many more things you could add to this bot including but not limited to games error handling and internationalization You may also want to learn more about Telegram bots And here are some resources to advance your knowledge about serverless computing Cyclic vs HerokuConsiderations for Serverless Active Active RoutingHow to Fail at Serverless Serverless is StatelessCreating and Deploying a RESTful API on Serverless Infrastructure 2023-01-02 18:36:14
海外TECH DEV Community Stylify CSS: Code your SvelteKit website faster with CSS-like utilities https://dev.to/machy8/stylify-css-code-your-sveltekit-website-faster-with-css-like-utilities-l7a Stylify CSS Code your SvelteKit website faster with CSS like utilitiesStylify SvelteKit Style your SvelteKit website faster with Stylify Don t study selectors and syntax Use pure CSS syntax and get generated CSS with advanced optimization for production For easier start you can check out the Stylify Stackblitz playground Stylify CSS IntroductionStylify is a library that uses CSS like selectors to generate optimized utility first CSS based on what you write CSS like selectorsNo framework to studyLess time spent in docsMangled amp Extremely small CSSNo CSS purge neededComponents Variables Custom selectorsIt can generate multiple CSS bundles SvelteKit SetupThe easiest way to Setup the SvelteKit is using CLI Run yarn create svelte latestThen cd appThis way you will get the default SvelteKit application skeleton Stylify CSS IntegrationInstall the stylify unplugin package using NPM or Yarn yarn add stylify unpluginnpm i stylify unpluginOpen the vite config js and copy the following content into it import sveltekit from sveltejs kit vite import stylifyVite from stylify unplugin const stylifyPlugin stylifyVite bundles outputFile src stylify css files src svelte const config plugins stylifyPlugin sveltekit export default config The last step create src routes layout svelte with the following content stylify css lt script gt import stylify css lt script gt lt slot gt In case you have created more bundles for example for pages you have to add paths to those generated CSS files into correct Svelte files Styling the websiteIf you copy the code below into the src routes page svelte and run yarn dev you will get a styled Hello World text lt main class max width px margin auto gt lt h class text align center margin top px font size px gt Hello World lt h gt lt main gt Stylify watches any change in the files that matches the mask in the bundle files and generates CSS into the src stylify css If you add for example color blue the CSS will be automatically updated Go ahead and try Stylify CSS directly on Stackblitz com ComponentsTo avoid bloated templates with utilities you can usecomponents directly in files where they are used through content options expects javascript object without brackets or in the compiler config lt stylify components container max width px margin auto title text align center margin top px font size px stylify components gt lt main class container gt lt h class title gt Hello World lt h gt lt main gt VariablesIf you like clean code you also want to avoid hardcoded values in selectors Variables can be defined in the same way as components lt stylify variables titleFontSize px containerWidth px stylify variablesstylify components container max width containerWidth margin auto title text align center margin top px font size titleFontSize stylify components gt lt main class container gt lt h class title gt Hello World lt h gt lt main gt Building for productionIf you run yarn build yarn preview the svelte markup will be mangled into this lt main class a gt lt h class b gt Hello World lt h gt lt main gt The CSS is shortened too root titleFontSize px containerWidth px c a max width px d a margin auto e b text align center f b margin top px g b font size px Stackblitz PlaygroundGo ahead and try Stylify CSS SvelteKit on Stackblitz You can customize the build above however you want ConfigurationThe examples above don t include everything Stylify can do Define componentsAdd custom selectorsConfigure your macros like ml px for margin leftDefine custom screensYou can map nested files in the templateAnd a lot moreFeel free to check out the docs to learn more Let me know what you think If you like the idea let me know that by starring Stylify repo ️ I will be happy for any feedback The Stylify is still a new Library and there is a lot of space for improvement 2023-01-02 18:14:54
Apple AppleInsider - Frontpage News Developers cautiously welcome prospect of third-party app stores https://appleinsider.com/articles/23/01/02/developers-cautiously-welcome-prospect-of-third-party-app-stores?utm_medium=rss Developers cautiously welcome prospect of third party app storesUnless something changes the EU s Digital Markets Act will effectively force Apple to allow alternatives to the App Store AppleInsider asked developers what they think ーand what they re planning to do Apple continues to oppose being required to allow alternatives to its iOS App Store but reportedly it is preparing for that eventuality Software and services engineers at Apple are believed to be preparing for the European Union s Digital Markets Act which could require third party app stores by Overall there appears to be at least an acceptance by developers that such a move will happen In some cases there is an active appetite for what third party app stores could bring though among the longest serving developers there is a cautious wariness Read more 2023-01-02 18:26:47
Apple AppleInsider - Frontpage News Stolen AirPods give up thief's location with Find My https://appleinsider.com/articles/23/01/02/stolen-airpods-give-up-thiefs-location-with-find-my?utm_medium=rss Stolen AirPods give up thief x s location with Find MyPolice were able to apprehend four men who stole a Texas man s car and other property after tracking the thieves via AirPods Second generation AirPods ProDawayne Arrington was the victim of an overnight theft discovering at his Leon Valley San Antonio home that someone had stolen his car After also discovering his work van was burgled overnight he switched from preparing to go to the gym to a crime fighting Read more 2023-01-02 18:28:03
ニュース @日本経済新聞 電子版 テスラ、22年のEV世界販売131万台 40%増も目標未達 https://t.co/pMf9D120m2 https://twitter.com/nikkei/statuses/1609986308113567746 世界販売 2023-01-02 18:53:42
ニュース BBC News - Home Perth hotel fire: Three dead in blaze at New County Hotel https://www.bbc.co.uk/news/uk-scotland-tayside-central-64144080?at_medium=RSS&at_campaign=KARANGA scottish 2023-01-02 18:02:47
ニュース BBC News - Home Some A&Es in complete state of crisis, warn health chiefs https://www.bbc.co.uk/news/health-64142614?at_medium=RSS&at_campaign=KARANGA causes 2023-01-02 18:22:49
ニュース BBC News - Home Pele's funeral: Brazil legend lying in state in Santos' stadium https://www.bbc.co.uk/sport/football/64145207?at_medium=RSS&at_campaign=KARANGA santos 2023-01-02 18:03:50
ニュース BBC News - Home Swansea City 1-2 Burnley: Ian Maatsen double seals leaders' sixth straight win https://www.bbc.co.uk/sport/football/64092505?at_medium=RSS&at_campaign=KARANGA Swansea City Burnley Ian Maatsen double seals leaders x sixth straight winLeaders Burnley claim a sixth straight Championship victory as Ian Maatsen s spectacular first half double secures a win at Swansea City 2023-01-02 18:01:12
ビジネス ダイヤモンド・オンライン - 新着記事 リーダー経験が一度もない人に決定的に欠けていること - 時間最短化、成果最大化の法則 https://diamond.jp/articles/-/314415 リーダー経験が一度もない人に決定的に欠けていること時間最短化、成果最大化の法則大反響【日経新聞掲載】有隣堂横浜駅西口店「週間総合」週連続ベスト入り残業しているのにさっぱり仕事が終わらない人と、定時で帰るのに成績Noの人。 2023-01-03 03:55:00
ビジネス ダイヤモンド・オンライン - 新着記事 【あなたはやってない?】空気の読めない人が「会話」でやりがちなこと3選 - おもろい話し方 https://diamond.jp/articles/-/315354 高い 2023-01-03 03:45:00
ビジネス ダイヤモンド・オンライン - 新着記事 【神様】にも得意分野がある! 運がいい人、お金持ちの人は知っている神社開運の作法 - 旬のカレンダー https://diamond.jp/articles/-/314449 【神様】にも得意分野がある運がいい人、お金持ちの人は知っている神社開運の作法旬のカレンダー「今日、何する」「どこ行く」「何食べる」と思ったとき、開くと必ず答えが見つかる書籍、『旬のカレンダー』。 2023-01-03 03:40:00
ビジネス ダイヤモンド・オンライン - 新着記事 「ラオスってどんな国?」2分で学ぶ国際社会 - 読むだけで世界地図が頭に入る本 https://diamond.jp/articles/-/314908 2023-01-03 03:35:00
ビジネス ダイヤモンド・オンライン - 新着記事 ブログ初心者がやりがちな「NG行為」2選 - ブログで5億円稼いだ方法 https://diamond.jp/articles/-/315398 行為 2023-01-03 03:25:00
ビジネス ダイヤモンド・オンライン - 新着記事 【強運な人は知っている】2023年にはじめるべき新習慣ベスト1 - 佐久間宣行のずるい仕事術 https://diamond.jp/articles/-/315024 佐久間宣行 2023-01-03 03:20:00
ビジネス ダイヤモンド・オンライン - 新着記事 【ワークマン仕掛け人・新年特別講義】 ホウ・レン・ソウを禁止したら業績が一気に伸びたワケ - ワークマン式「しない経営」 https://diamond.jp/articles/-/314011 【ワークマン仕掛け人・新年特別講義】ホウ・レン・ソウを禁止したら業績が一気に伸びたワケワークマン式「しない経営」たちまち万部今、最も注目を集める急成長企業ワークマン。 2023-01-03 03:15:00
ビジネス ダイヤモンド・オンライン - 新着記事 【1分間でやる気アップ】誰かに話したくなる「モチベーション」の話【エピソード5】 - 勉強が面白くなる瞬間 https://diamond.jp/articles/-/315408 韓国で社会現象を巻き起こした『勉強が面白くなる瞬間』。 2023-01-03 03:10:00
ビジネス ダイヤモンド・オンライン - 新着記事 【スケジューリングのプロ】に学ぶ「予定管理3つのテクニック」とは? - 超ミニマル主義 https://diamond.jp/articles/-/315399 【スケジューリングのプロ】に学ぶ「予定管理つのテクニック」とは超ミニマル主義今回ご紹介するのは、スケジュール管理の精度を高めるためのティップスと大切な考え方。 2023-01-03 03:05:00
ビジネス ダイヤモンド・オンライン - 新着記事 【整体のプロ】が放っておけない「アウトな朝習慣」とは? - すごい自力整体 https://diamond.jp/articles/-/315388 【整体のプロ】が放っておけない「アウトな朝習慣」とはすごい自力整体年齢とともに、ますます硬くなる体、痛くて上がらない肩、腰や股関節、ひざの痛み、体のゆがみ、むくみ……。 2023-01-03 03:05:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)