投稿時間:2021-06-13 10:16:55 RSSフィード2021-06-13 10:00 分まとめ(21件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
TECH Techable(テッカブル) バーチャルヒューマンが腕時計の魅力を伝えるVRの街「CITIZEN Timeless City」 https://techable.jp/archives/156292 citizentimelesscity 2021-06-13 00:00:55
python Pythonタグが付けられた新着投稿 - Qiita pythonエンジニア認定試験受験記パート2 https://qiita.com/Katie_Code/items/136f8e106dcee699e3e7 よってmaplambdaxxrangeについてはrangeでまで抜き出した値がlambdaに都度代入されるその上でその結果をlistに渡しているので結果としてはxをリストに入れているlist故に実行結果としては以下のようにの冪乗のリストが出来上がる実行結果タプルで複数の値をリスト内包表記できると話xyforxinforyinifxyパッと何をやっているのか分かりにくいが、一番大事なのはifxyの部分であるつまりxとyがnotイコールだったら最初のタプルに値を入れて良いというコードである。 2021-06-13 09:35:38
python Pythonタグが付けられた新着投稿 - Qiita 【Django】論理削除でもCASCADE deleteしたい! https://qiita.com/donaisore/items/06791c3634547f8eec93 おわり少し強引に実装してしまったかなと思ってはいますが「論理削除でも、関連テーブルのレコードを削除したい」を実現することができました。 2021-06-13 09:10:01
python Pythonタグが付けられた新着投稿 - Qiita STM32L010とWS2812BとPython 3.7.6(PC)で光らす。 https://qiita.com/caa45040/items/5e015c03383a4953c557 STMLとWSBとPythonPCで光らす。 2021-06-13 09:07:28
js JavaScriptタグが付けられた新着投稿 - Qiita stack machineを愛でる。 その5 https://qiita.com/ohisama@github/items/2323b60567a89707170e stackmachineを愛でる。 2021-06-13 09:45:21
js JavaScriptタグが付けられた新着投稿 - Qiita stack machineを愛でる。 その4 https://qiita.com/ohisama@github/items/fc0815497902d0a368bf 変数に、テキストを代入するには、setを使います。 2021-06-13 09:40:14
js JavaScriptタグが付けられた新着投稿 - Qiita stack machineを愛でる。 その3 https://qiita.com/ohisama@github/items/c1dd9cf4033678d9635c stackmachineを愛でる。 2021-06-13 09:28:17
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) unity オンラインランキング 送信押せない https://teratail.com/questions/343733?rss=all unity 2021-06-13 09:59:32
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) php簡易掲示板 投稿表示されない https://teratail.com/questions/343732?rss=all php簡易掲示板投稿表示されない前提・実現したいことここに質問の内容を詳しく書いてください。 2021-06-13 09:50:13
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) HTMLのdivタグについて https://teratail.com/questions/343731?rss=all divタグについてなのですが、学習している感じかなり使うように感じています。 2021-06-13 09:42:46
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Python ノードの全選択 https://teratail.com/questions/343730?rss=all Pythonノードの全選択前提・実現したいことclassに作った要素を全て選択する方法を知りたいここに質問の内容を詳しく書いてください。 2021-06-13 09:39:05
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) SwiftUIで多角形のImageに外枠をつける方法をご教授ください。 https://teratail.com/questions/343729?rss=all SwiftUIで多角形のImageに外枠をつける方法をご教授ください。 2021-06-13 09:10:40
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 文字列を指すポインタの交換 https://teratail.com/questions/343728?rss=all 文字列を指すポインタの交換前提・実現したいこと『新・明解C言語nbspポインタ完全攻略』において、文字列を指すポインタの交換プログラムpListを試しています。 2021-06-13 09:08:27
AWS AWSタグが付けられた新着投稿 - Qiita AWS(Elastic Beanstalk) + docker + flaskでwebアプリ(mecab利用)を公開 https://qiita.com/NomuraS/items/c5113db5488da679e7df EBでアプリ公開したいので、そのページから「ウェブアプリケーションの構築ElasticBeanstalk」を選択してその先で表示される画面で環境を構築してサンプルコードで一旦アプリを動かして確認しておく。 2021-06-13 09:07:44
Docker dockerタグが付けられた新着投稿 - Qiita AWS(Elastic Beanstalk) + docker + flaskでwebアプリ(mecab利用)を公開 https://qiita.com/NomuraS/items/c5113db5488da679e7df EBでアプリ公開したいので、そのページから「ウェブアプリケーションの構築ElasticBeanstalk」を選択してその先で表示される画面で環境を構築してサンプルコードで一旦アプリを動かして確認しておく。 2021-06-13 09:07:44
Ruby Railsタグが付けられた新着投稿 - Qiita ActionTextの投稿機能をRspec(system spec)でテストする https://qiita.com/KH14/items/7204fd1453b0ed9a9802 articlesテーブルにはtitle属性があり、ActionTextを使ってcontent本文画像付きもOKを作成できるようにしている。 2021-06-13 09:26:05
海外TECH DEV Community How to become a Senior Developer https://dev.to/krowser/how-to-become-a-senior-developer-20po How to become a Senior DeveloperThe Road From Junior to Senior Developer Being a programmer is a great thing For me there s nothing better than working in software engineering It s highly satisfying to write code that works to develop products that potentially billions of people are using every day think Facebook to have the opportunity to work with the smartest minds on this planet and to get paid well for what I love to do A career in software engineering is often divided into phases Most people start as junior developers then later become mid level and senior devs But is it wise to follow this path And what s expected of you at each career step How do you progress I have been down that road and beyond and I want to share my experiences thoughts and opinions with you ーproviding some guidance for your own careers Getting Your First JobLet s start with the good news Everyone has to start somewhere No one is born an expert developer It s a misconception ーoften fueled by job listings that search for junior developers with ten years experience in four different JavaScript frameworks like React which isn t even that old and three database technologies ーthat junior developers should already be expert programmers That s absolute garbage ーdon t let it affect you or your self confidence Of course getting your first job as a developer is far from an easy task But you can do things that will work in your favor Apply for internshipsInternships are a great way to gain work experience For many people they re the launchpad for their first permanent role Don t just look for money Yes corporations like Google Facebook or Palantir pay their interns five figure salaries But the competition is extremely strong and smaller companies can teach you valuable things as well That being said don t sell yourself short Have a part time jobA part time job during college where you can practice your coding skills is also great Look for job postings on and offline Create a portfolioA portfolio consists of projects for example javascript projects that you ve worked on that you can show to potential employers It s a good thing if you have one but not as important as many people want to make you believe Portfolios don t get jobs ーit s the people behind them Don t expect to land a job because you have one However it can help you to get a job interview Contribute to open source projectsMany people think that in order to contribute to open source projects they already have to be expert developers Go to a boot campBootcamps have evolved over the last decade They provide a compact way to teach you the basics of software development They re especially aimed at people without a background in computer science They range from three months to a year and are not generally cheap Junior Developer ーObserve and LearnIf things played out well for you and you landed your first job ーgreat If it takes longer than you have expected ーdon t worry hang in there good things take time Beginners tend to think that writing code that works is the same as writing good code They can also think that everything needs to be fancy and overly complicated because that s how the pros do it I encourage you to make mistakes but also to learn from them Here s some important advice for the early phase of your career Ask questionsI cannot stress this too much Most junior devs simply don t ask enough questions This is the time to learn to observe to suck everything in If you don t ask questions you will not only miss great opportunities to becoming a better programmer but people might also think that you re not interested in them or their work Or even worse that you think you know everything better You don t Even if you do ーdon t show it Show them respect and be smart about it This is your chance to lay the foundations for your future Observe how teams functionThe chances are you joined an existing team in your first role as a junior developer It s highly uncommon that you work on your own right away so don t waste the opportunity to observe your team members and how they interact with each other Are there other junior devs Senior devs that could potentially mentor you Who seems willing to help others out and who doesn t When are the important meetings like dailies retrospectives or plannings and what is expected from you and the team Get familiar with an IDEMaybe you already have experience with one or another IDE when you are starting your first job However teams and projects have their own setups when it comes to development activities Maybe they use VS Code maybe PHPStorm maybe something else You want to get familiar with the tools as soon as possible Ask what linting rules the team uses and practice shortcuts to becoming more efficient when coding Learn how to write maintainable clean codeWhen you start writing code no one will expect it to be perfect right from the start what s perfect code anyway What you want is to write code in a way that others find easy to understand and that speaks for itself You want variable names that speak for themselves and you want to keep functions short Don t do fancy things to impress others and always keep in mind that you re not the only one working on the codebase Learn how version control software worksMost companies work with Git as their primary version control system You want to learn the basic concepts right from the beginning because this is a vital skill for the rest of your career And a potentially contentious point if you work on a wrong branch or push untested code to production never do this Search for a mentorMany companies have established mentorship programs that pair junior devs with more experienced developers But if that s not present in your company you should try to find someone on your own preferably from within the team or company If that s not possible have a look on platforms like Codementor io or check the listing board here on dev toEmbrace the power of code reviewsCode reviews are mandatory in many organizations to reduce errors and prevent bugs For you the starting developer they re a great opportunity to become better Approach them from two sides On the one hand you want to review the code of others as much as possible and ask for what you don t understand On the other hand others review your code and don t take their potential criticism personally but as a chance to improve your coding skills Pair program if possiblePair programming is also a vital method of transferring knowledge While it might be a bit frightening to directly work with someone else on the same machine I can only recommend to do it Don t be afraid to take over the keyboard and make mistakes ーyou learn from them Some people recommend taking on side projects to practice skills and learn new things But I would advise you to do that later in your career If you are just starting believe me there s so much to learn that you don t need anything else Mid Level Developer ーIt s Not All About CodeAfter your first two years in software engineering you should call yourself a developer This is the position where many people stay throughout their careers And there s nothing wrong with that Attention This is not just about the code you write but the ability to work in and contribute to a team and to understand software development workflows and processes You should also understand common design patterns and understand the KISS Keep It Stupid Simple DRY Don t Repeat Yourself and SOLID principles You should be familiar with IDEs and version control software You should be able to write good code on your own and to tackle more challenging tasks There s nothing wrong with being a developer that works on routine tasks fixes bugs and contributes to the codebase In fact this is what the majority of people are doing every day There are a lot of developers out there that love their jobs and are getting paid well Now would be a good time to try out other languages or frameworks You could start a side project on your own or have a look at open source projects Senior Developer ーTime for MentoringMany people think that a senior developer is someone who writes perfect code in a fraction of time without any errors A one person army building entire web applications on their own producing deliverable pieces of software every day Sadly many companies are still looking for this fairy creature They should look for something else As an experienced developer you should be able to see the big picture You constantly have to ask “why Why are we using a particular language Data storage A specific architecture Senior developers won t say that language x is better than language y Instead they understand that for a particular problem it would be more appropriate to use language x They care for performance They write code that s maintainable and leaves no technical debt for others They also know when it makes sense to write code that seems amateurish and that violates the DRY principle but helps others to understand it or leads to better performance The most important deliverable for a senior developer is more senior developers One of the most important attributes of a senior developer if not the most important attribute is strong social skills In the end most projects fail because of a lack of communication It s your responsibility to take care of less experienced devs ーto mentor them But you should also be able to talk to stakeholders and executives and explain things in a way people with less knowledge can understand To be a team player who strives for long term success Senior developers understand that working in software engineering is not solely about instructing computers to execute bits and bytes It s also about communicating with humans Final ThoughtsThere s no objective way to determine if one is a junior mid level or senior developer After all titles are often used as a guideline to salaries ーthey depend on the company you work for Real experience won t come from a title but from what you ve learned from mistakes and failures At the beginning of your careers be patient Learn the basic patterns of software engineering and work on your technical skills And understand the difference between Java and JavaScript When you gain experience try to understand the bigger picture Improve your soft skills help others out Be bold and open minded Don t base decisions on personal opinions but on what works best to solve complex problems Finally don t hang onto those titles too much A real senior developer doesn t care about the title ーthey care about the impact they have on people products and companies and their legacy In the end we re just people with strengths and weaknesses We struggle we fail we get knocked to the ground But we get back on our feet to continue doing what we love ーdeveloping software 2021-06-13 00:52:42
海外TECH DEV Community Building An E-commerce Telegram Bot Using Python and Fauna. https://dev.to/curiouspaul1/building-an-e-commerce-telegram-bot-using-python-and-fauna-1hj5 Building An E commerce Telegram Bot Using Python and Fauna This article will show you how to build a telegram bot for a small scale business owner This bot will be pretty similar to the popular platform WhatsApp Business in terms of its features We will see how to implement those features and set up our database on Fauna s serverless system to host user data Before we begin let me inform you that I will be calling this bot telegram business for the rest of this tutorial WHAT TELEGRAM BUSINESS CAN DOFirst off there are two kinds of users customers and business owners The features of the bot are classified according to the typeof users allowed on the platform The following includes the features of telegram business CUSTOMER FEATURES Customers can view businesses from four different categories Customers can view products from any of these businesses Customers can place an order on a product BUSINESS OWNER FEATURES Business owners can create a catalog and add products Business owners will get notified when a user places an order Pre RequisitesFor this tutorial I m going to be using Python as well as Fauna s platform To follow this tutorial you ll want to have Python installed and have an account with Fauna If you do not have a Fauna account you can signup on the website here It is in your best interest to have a fundamental knowledge of Python to follow this tutorial I ll also be using Cloudinary to store product images You can sign up for a free Cloudinary account here Here s a detailed list of the things we need for this bot PythonA fauna accountA cloudinary account Preparing the databaseThe first thing we want to do is to set up our database on Fauna Head over to fauna com and log in to your dashboard Once logged in click on the “New Database button on the dashboard to create a new database This will bring you to a page just like in the image above Fill in the required fields and click on “Save to create a new database for our bot Creating CollectionsNext we ll create three collections for each entity on our platform Users Businesses and Products Click on “New Collection It should take you to a new page like the one below Call this one Users and hit the “Save button to create the collection After doing that create two other collections Business and Products Once you re done you should now have three collections show up on the collections menu option Let s move on to creating indexes for easy retrieval of information from our database Creating IndexesFor our e commerce system we re going to have to create several indexes to help with getting the information we need faster To create an index head over to the indexes menu option and click on the “New Index button to create a new index It should take you to a new page that looks similar to the one below The first index we want to make allows us to find users by their name So we ll pick the source collection which is the User collection for this first index and then give our index the name “user by name then we choose the term we want to search on which is the “name of the user and so we enter “name in the term field you can leave the values field empty as is Once done your form should look like the one below Next create three more indexes with the following information business by name source collection Business term name product by business source collection Product term sme business by category source collection Business term category Generating an API KEYOne last thing we need to get from Fauna is the API KEY for our database to send queries to it over the internet Head over to the Security option and click on the “New Key optionーit should take you to a new page with a form Click “Save and it ll generate a key for you to copy Copy that key and save it in a text file somewhere we ll use it later Building The Bot Talking with BotFatherTo build a Telegram bot we must register it with Telegram s bot father To create your bot open up Telegram and search for the bot father or simply click here to go to the bot father s chat Once there type “ start to begin a conversation with the botfather and it ll show you a list of commands that you can use to interact with it these commands can be typed or clicked on to execute them Choose the newbot command to create a new bot Once we do that botfather will ask for a name and then a username Once we do this the botfather will provide us with information about the new bot like the link to the bot and an access token which is what we need for now Copy this and save it somewhere Scripting Telegram BusinessWe ll start by creating a virtual environment for our project opening up your command prompt and changing the directory to your preferred location this should preferably be a new empty folder Once there create a virtual environment using any desired virtual environment manager in Python I m using virtualenv to create one called “env for example I ll run the following command virtualenv envNext we ll activate our virtual environment and install the following python packages Python telegram bot which helps us write code for controlling our bot Faunadb which is a Python package that helps us interact with Fauna s api from our scripts python dotenv which will help us read config variables easily Cloudinary a client library for our photo storage API Make sure to sign up for a cloudinary account and get your api key and secret from the dashboard We ll need those later on We ll start by creating the following files in our project folder handlers pymain pyconfig py envI ll split the implementation of the handlers into two parts Customer FunctionalitiesBusiness FunctionalitiesWe ll start with the business functionalities which includes the bot s interaction with users who are business owners The first thing we need to do is to add our tokens and keys from botFather cloudinary and Fauna to the env file as follows BOT TOKEN roAPI SECRET OcAGV API KEY FAUNA KEY f sZ J Gd QOnce this is done we move on to the config py file and in there we point some variables to these environment variables from the env file by reading them via the python dotenv package we installed earlier This package allows us to read environment variables from files and even directly from the command prompt import osfrom dotenv import load dotenvload dotenv TOKEN os getenv BOT TOKEN api secret os getenv API SECRET api key os getenv API KEY FAUNA KEY os getenv FAUNA KEY Now we can use these variables in our code without reading from the env file Next we begin with our handler methods and these will handle how the bot interacts with the users on Telegram We ll start with the handler methods responsible for managing the bot s interaction with users who sign up to be business owners The file for this code is handlers py and import the required dependencies from telegram import ReplyKeyboardMarkup ReplyKeyboardRemove Update InlineKeyboardButton InlineKeyboardMarkup from telegram ext import CommandHandler CallbackContext ConversationHandler MessageHandler Filters Updater CallbackQueryHandler from config import api key sender email api secret FAUNA KEY import cloudinaryfrom cloudinary uploader import uploadfrom faunadb import query as qfrom faunadb client import FaunaClientfrom faunadb errors import NotFoundWe ll add some of the boilerplate config for some of our dependencies so add the following after importing all these configure cloudinarycloudinary config cloud name curiouspaul api key api key api secret api secret fauna client configclient FaunaClient secret FAUNA KEY Define OptionsCHOOSING CLASS STATE SME DETAILS CHOOSE PREF SME CAT ADD PRODUCTS SHOW STOCKS POST VIEW PRODUCTS range The first config is for our Cloudinary instance and the second for our Fauna client instance the variables following that represent the states of the bot or at least the state that it could be in as users interact with it This is required by the “conversationhandler which is a method that allows us to script our bots in a way that makes their interaction with people more natural The names of each variable slightly indicate what state they represent For example the SME DETAILS state is tied to certain methods of asking the user for details of their business Adding Handler MethodsWe ll continue from this point by adding handler methods to our script The first handler method we need to add is the one that handles what takes place when we initiate a conversation with the bot via the start command The following lines of code are what gets called when someone uses the start command on our bot so add it to the handler code def start update context CallbackContext gt int print You called bot context bot chat id update message chat id bot send message chat id chat id text Hi fellow Welcome to SMEbot Please tell me about yourself provide your full name email and phone number separated by comma each e g John Doe JohnD gmail com return CHOOSINGLook at how I return a new state of the bot s conversation which is one of our predefined states from earlier This function sends back an intro message and requests information from the user The following state is CHOOSING and this state is tied to another method which takes the user input and parses it to make sure it is correct before using the info to sign a user up Then it prompts the user to pick what kind of user he she is i e a customer or business owner Add the following lines of code to add this method get data generic user data from user and storedef choose update context bot context bot chat id update message chat id create new data entry data update message text split if len data lt or len data gt bot send message chat id chat id text Invalid entry please make sure to input the details as requested in the instructions bot send message chat id chat id text Type start to restart bot return ConversationHandler END TODO Check if user already exists before creating new user new user client query q create q collection User data name data email data telephone data is smeowner False preference chat id chat id context user data user id new user ref id context user data user name data context user data user data new user data bot send message chat id chat id text Collected information succesfully n Which of the following do you identify as reply markup markup return CLASS STATEThis function takes the user input parses it and uses the result to save the user s information onto our database on Fauna by using the query method from the Fauna library to send a post request to the Fauna API which writes to the database We also store some information about the user in memory with the context user data attribute that we ll need later in other handler methods Lastly we return a response as well as a new conversation state this state CLASS STATE is where we ll determine what kind of user we re dealing with i e a customer or a business owner def classer update context bot context bot chat id update callback query message chat id name context user data user name if update callback query data lower sme update user as smeowner client query q update q ref q collection User context user data user id data is smeowner True bot send message chat id chat id text f Great name please tell me about your business provide your BrandName Brand email Address and phone number in that order each separated by comma each e g JDWears JDWears gmail com Mike Avenue Ikeja reply markup ReplyKeyboardRemove return SME DETAILS categories InlineKeyboardButton text Clothing Fashion callback data Clothing Fashion InlineKeyboardButton text Hardware Accessories callback data Hardware Accessories InlineKeyboardButton text Food Kitchen Ware callback data Food Kitchen Ware InlineKeyboardButton text ArtnDesign callback data ArtnDesign bot send message chat id chat id text Here s a list of categories available Choose one that matches your interest reply markup InlineKeyboardMarkup categories return CHOOSE PREFHowever the function sends a different response to the user if the user identifies as a customer instead There is a menu of categories for the customer to choose from in order to view the businesses under the chosen category If the user identifies as a customer these categories are sent as a response to the user and a new state is returned associated with customer functionalities Let s add a cancel command handler to help users cancel their interaction with the bot at any time Add the following function next Controldef cancel update Update context CallbackContext gt int update message reply text Bye I hope we can talk again some day reply markup ReplyKeyboardRemove return ConversationHandler ENDAt this point we can test our bot to see how it responds to our interactions In order to test the bot we need to register our handlers with the conversation handler method in main py and map them to each state as follows import handlersfrom telegram ext import CommandHandler CallbackContext ConversationHandler MessageHandler Filters Updater CallbackQueryHandler from config import TOKENupdater Updater token TOKEN use context True print updater dispatcher updater dispatcherdef main conv handler ConversationHandler entry points CommandHandler start handlers start states handlers CHOOSING MessageHandler Filters all handlers choose handlers CLASS STATE CallbackQueryHandler handlers classer fallbacks CommandHandler cancel handlers cancel allow reentry True dispatcher add handler conv handler updater start polling updater idle if name main main Save this go to your terminal and run the bot via the main py file as follows Once you run this command you might not see any immediate prompt from the terminal until you begin interacting with the bot Let s go to our bot and initiate a conversation Use the link that botFather provided you with or just search with the name of your bot in Telegram Once there use the start command or just click the start button on the chat with your bot to initialize a conversation You should see your bot respond as such Follow the prompt type in the required information and send it as a message to activate the next state of the conversation which is going to ask you to pick what kind of user you identify as an SME owner or a customer Choosing the SME option prompts us to enter details about our “business as described in the classer method we defined earlier on However if we chose the customer option as our preference then the bot responds with a list of category options to choose from This is as far as our bot can go since we haven t added the handler methods for the remaining functionalities we want So let s continue with scripting the bot The following is a series of handler methods that are responsible for all business functionalities Add the following handler methods in the order that they are below I am listing them out based on their functionalities and some may involve more than one handler method Collecting Business Details and Storing For this there are two functions the first takes user input from the last phase for a business parses it and stores the data in memory passes the data to the following handler method and finally prompts the user to pick a category under which their business falls The second one takes all the data and uses it to create a new business document in our Faunadb instance prompts the user to add a new product and then returns a new conversation state which is associated with the handler methods responsible for adding products to the newly created business def business details update context bot context bot chat id update message chat id data update message text split if len data lt or len data gt bot send message chat id chat id text Invalid entry please make sure to input the details as requested in the instructions return SME DETAILS context user data sme dets data categories Clothing Fashion Hardware Accessories Food Kitchen Ware ArtnDesign Other categories InlineKeyboardButton text Clothing Fashion callback data Clothing Fashion InlineKeyboardButton text Hardware Accessories callback data Hardware Accessories InlineKeyboardButton text Food Kitchen Ware callback data Food Kitchen Ware InlineKeyboardButton text ArtnDesign callback data ArtnDesign markup InlineKeyboardMarkup categories one time keyboard True bot send message chat id chat id text Pick a category for your business from the options reply markup markup return SME CATdef business details update update context bot context bot chat id update callback query message chat id choice update callback query data create business new sme client query q create q collection Business data name context user data sme dets email context user data sme dets address context user data sme dets telephone context user data sme dets category choice lower context user data sme name context user data sme dets context user data sme id new sme ref id context user data sme cat choice button InlineKeyboardButton text Add a product callback data choice lower bot send message chat id chat id text Business account created successfully let s add some products shall we reply markup InlineKeyboardMarkup button return ADD PRODUCTSAdding Products This involves two handler methods as well the first one prompts the user and gives instructions on how the product can be added while the second one takes the user input parses it and uses it to create a new product by adding it as a new document to our Product collection on our Fauna instance def add product update context bot context bot chat id update callback query message chat id bot send message chat id chat id text Add the Name Description and Price of product separated by commas as caption to the product s image return ADD PRODUCTSdef product info update Update context CallbackContext data update message bot context bot photo bot getFile update message photo file id file open product image wb photo download out file data update message caption split upload image to cloudinary send photo upload product image width height crop thumb create new product newprod client query q create q collection Product data name data description data price float data image send photo secure url sme context user data sme name sme chat id update message chat id category context user data sme cat add new product as latest client query q update q ref q collection Business context user data sme id data latest newprod ref id context user data product data newprod data button InlineKeyboardButton text Add another product callback data context user data sme name update message reply text Added product successfully reply markup InlineKeyboardMarkup button return ADD PRODUCTSThis concludes the business part of the bot We will now add more handler methods to cover the customer functionalities as follows View Businesses From any Category This involves a handler method that takes the user s choice and uses our business by category index to find all businesses in that category and then displays a list of the businesses with their latest merchandise as a thumbnail along with two options CUSTOMERdef customer pref update context bot context bot chat id update callback query message chat id data update callback query data print data get all businesses in category try smes client query q map lambda var q get var q paginate q match q index business by category str data lower print smes for sme in smes data button InlineKeyboardButton text View Products callback data sme data name InlineKeyboardButton text Select for updates callback data pref sme data name if latest in sme data keys thumbnail client query q get q ref q collection Product sme data latest print thumbnail bot send photo chat id chat id photo thumbnail data image caption f sme data name reply markup InlineKeyboardMarkup button else bot send message chat id chat id text f sme data name reply markup InlineKeyboardMarkup button except NotFound button InlineKeyboardButton text Select another Category callback data customer bot send message chat id chat id text Nothing here yet reply markup InlineKeyboardMarkup button return CLASS STATE return SHOW STOCKSView Products This is quite self explanatory and it involves listing out all products belonging to any business that the user has decided to view We are able to display all products from a business with the aid of the products by business index we created on our Fauna instance earlier what this means is that we can send a query to fetch all the products that a business has on its catalogue with the products by business index and then display the results to the user def show products update context bot context bot chat id update callback query message chat id data update callback query data if pref in data data data split replace print data user client query q get q ref q match q index user by name context user data user data name update preference client query q update q ref q collection User user ref id data preference user data preference data button InlineKeyboardButton text Vieew more businesses category callback data customer bot send message chat id chat id text Updated preference successfully return CLASS STATE products client query q map lambda x q get x q paginate q match q index product by business update callback query data print products if len products lt bot send message chat id chat id text Nothing here yet user hasn t added any products check back later return CLASS STATE for product in products data context user data sme id product data sme button InlineKeyboardButton text Send Order callback data order product ref id InlineKeyboardButton text Contact business owner callback data contact product data sme bot send photo chat id chat id photo product data image caption f product data name nDescription product data description nPrice product data price reply markup InlineKeyboardMarkup button return POST VIEW PRODUCTSThis block of code is responsible for fetching all the products from a business and displaying them to the user with the option of placing an order or contacting the business owner Place Order and Contact Details of Business Owner The following block is responsible for placing an order and providing the customer with the business owner s details When a user places an order the bot sends a message to the business owner containing information about the product that will sold and the prospective buyer s Telegram contact def post view products update context bot context bot chat id update callback query message chat id data update callback query data product client query q get q ref q collection Product data split data if order in data bot send message chat id product sme chat id text Hey you have a new order bot send photo chat id product sme chat id caption f Name product name n nDescription product description n nPrice product price f n n Customer s Name context user data user name photo product image bot send contact chat id product sme chat id phone number context user data user data telephone first name context user data user data name bot send message chat id chat id text Placed order successfully elif contact in data sme client query q get q match q index business by name product sme data bot send message chat id chat id text f Name sme name n nTelephone sme telephone n nEmail sme email Testing The BotWe can save the changes to our handlers py file and then move on to register the newly added methods to our conversation handler in main py as with the first few functions as follows import handlersfrom telegram ext import CommandHandler CallbackContext ConversationHandler MessageHandler Filters Updater CallbackQueryHandler from config import TOKENupdater Updater token TOKEN use context True print updater dispatcher updater dispatcherdef main conv handler ConversationHandler entry points CommandHandler start handlers start states handlers CHOOSING MessageHandler Filters all handlers choose handlers CLASS STATE CallbackQueryHandler handlers classer handlers SME DETAILS MessageHandler Filters all handlers business details handlers SME CAT CallbackQueryHandler handlers business details update handlers ADD PRODUCTS CallbackQueryHandler handlers add product MessageHandler Filters all handlers product info handlers CHOOSE PREF CallbackQueryHandler handlers customer pref handlers SHOW STOCKS CallbackQueryHandler handlers show products handlers POST VIEW PRODUCTS CallbackQueryHandler handlers post view products fallbacks CommandHandler cancel handlers cancel allow reentry True dispatcher add handler conv handler updater start polling updater idle if name main main Update the code in main py so it has the other functions we added as shown above When completed we can run our code from the cmd like before to test our bot Once it s up and running head over to the bot on Telegram and create a business and add products You could also use another telegram account to interact with the bot as a customer and place orders The second image shows what the business owner sees each time a customer places an order ConclusionIn this article we ve seen how to use Fauna s serverless platform to create and host a database along with indexes and collections We saw how to generate an API key for communicating with our database from within other python apps which in this case was telegram business We saw how to build a telegram bot from scratch using Python and the required libraries The demo from this article isn t the end for telegram business however I ll be adding more features and deploying it live soon enough I m hoping this article has inspired you to think of new ways to create solutions to problems around you and when you finally find a solution you know you can always count on Fauna to help host your data without hassle like it has helped us in this article 2021-06-13 00:18:14
海外科学 BBC News - Science & Environment Swiss to vote in pesticide ban referendum https://www.bbc.co.uk/news/world-europe-57457384 damage 2021-06-13 00:33:59
ニュース BBC News - Home Disruption to shipping could delay Christmas orders https://www.bbc.co.uk/news/business-57446437 blockages 2021-06-13 00:52:15
ニュース BBC News - Home Swiss to vote in pesticide ban referendum https://www.bbc.co.uk/news/world-europe-57457384 damage 2021-06-13 00:33:59

コメント

このブログの人気の投稿

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

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

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)