Python shopping bot

Python shopping bot DEFAULT

Related Posts

I am going to show you what you need to do to create a Python bot of your own by giving you a general recipe that you can extend at your will.

What is a Python Bot

A Python bot is a script that runs 24/7 hours, without needing to sleep or rest, and can perform any kind of automated task that is doable via a web browser and with an internet connection. 

Bots have been around since the internet was invented. The most famous bots are those that search the internet, to find quality websites like this one, and then you have stock market scalping bots, automated shopping bots, chatbots, and the more infamous ones are the GPUs scalping bots! And probably why you are here.

Beating the GPU Scalpers

We have all been trying to buy the latest Nvidia GPUs like the RTX 3060, RTX 3070, 3080, and RTX 3090 for those who can afford them. Also, the most popular AMD CPUs are pretty hard to buy. This is all because of the general shortage of silicon, which is affecting, not only computing but also the whole automotive industry, and other sectors.

Also, the greedy scalpers are not helping at all.

Crypto Miners are scalping too

The demand is there because of crypto mining as well. Bitcoin is skyrocketing in value and more and more people are buying GPUs, not for gaming, not for Deep Learning, but for mining Bitcoin! And let’s face it, the miners will have a lot more resources than a “simple” scalper who is trying to sell for a profit a GPU on eBay.

Why create your own Python Bot

The most important reason for creating your own python bot is that “knowledge is power”. By being able to make your own Python bot the possibilities are endless. 

Not only you will be able to beat the GPU scalpers and get that nearly impossible to buy GPU, but you can also collect all kinds of useful data from the internet with Data Scraping, which is extremely powerful and useful for a variety of fields that feed on data(e.g. machine learning). 

You can also use bots to deliver useful services for the internet too. For example, a few years ago when I was trying to pass my driving license, I couldn’t book my driving test without waiting 3 months for an available slot because there was huge demand for driving tests and not too many slots available. But then sometimes someone would cancel their driving test at the last minute, opening up an available slot. But there was no way for me to know, without being on the website 24/7.

I then found a website that would scalp the slots for me, for a small fee. And voila, after I failed my driving test(UK — not USA), I was able to book my driving test again for the following week.

Whoever created that service, made a huge profit and at the same were able to provide useful service using an “ethical” bot.

You don’t know how to code in Python

If you don’t know how to code or you don’t know Python, I recommend you to learn it. Python is an extremely popular language applicable to a lot of fields. You can’t go wrong with it. And it turns out many bots on the internet are written in Python, so you must learn Python!

There are plenty of Python courses available on the internet. My recommendation is that you take one basic Python course to get started, in order to learn the basics of the language. There are so many good courses for Python. Probably the most popular is a course by Dr. Chuch Severance from the University of Michigan. If I was starting to learn Python today, he would be my first stop:

Don’t get discouraged by the 13h in the course, every single minute will be worth it. And definitely don’t waste more time on other courses. You just need one course to learn Python. Nothing more.

Once you can code in Python, most of the learning will be done by doing.

How to create a simple Python bot

Enough of talking. Let’s create a simple Python bot, which you can use as your starting point. This python bot will check for stock of the latest RTX series from the newegg.com website as an example.

Installing Python

Before we do any Python Development, you need to somehow install Python on your computer. There are several methods on how to install Python. 

Installing Standalone Python 

You can install Python directly by downloading the correct installer for your OS (Windows or Mac) from python.org and installing it. Please see the instructions on how to do that here.

Installing Python with Anaconda

Even though it is perfectly acceptable to install Python standalone, many choose to install Python with Anaconda. And why is that? 

Why Anaconda?

Anaconda is a toolkit that includes Python and libraries that are are the favorites for most Data Science, Machine learning, web scraping projects on the web. And it already includes Jupyter Lab, a web-based IDE, very useful for the development of our Python Bot. 

With Anaconda, we can run different versions of Python in isolated environments which only contain the Python libraries and versions that we need. While still having access to pip we also have access to the conda package manager which allows us to install pre-compiled Python libraries. Contrast this to pip which instead of providing the compiled binary of a library, needs to compile any library from wheels during installation.

How to Install Anaconda

It is possible to install Anaconda in Windows, MacOS, or Linux. We will install Anaconda in Windows 10 for this tutorial. Before starting make sure that you have at least 3GB of disk space available.

Downloading the Installer

First, let’s download the installer from the Anaconda website.

Starting the installation

At this point, you have a choice to install for yourself or for “All Users”. Just go with the recommended option, and install it just for yourself in your own userspace.

Adding Anaconda to Windows PATH environment variable

At this stage, you will want to tick the checkbox “Add Anaconda3 to my PATH variable”. This will require Administration privileges. 

You will notice a warning, which is highlighted in red, once you tick the box. If you are the main user of your computer and you don’t have any previously installed versions of Anaconda or Python, then you shouldn’t have any issues. In the worst-case scenario, it is always possible to delete the variable from your PATH at a later stage.

And finally, the installation completes:

Starting Anaconda Navigator

To get started we open the Anaconda Navigator:

Creating an environment in Anaconda

To create a new Anaconda Environment, click on Environments:

And here we can type gpu_python_bot in the environment name. One of the advantages of Anaconda is that we can have multiple environments using different versions of Pythons. But in our case Python 3.8 is ok. So we can leave the default value.

Installing the required libraries

To follow the tutorial we need to install the following libraries:

  • selenium
  • python-chromedriver-binary
  • bs4 ( Beautiful Soup)
  • pandas

Let’s open a command prompt and activate the newly created environment:

$ conda activate gpu_python_bot
> (gpu_python_bot)....

Now we can install the required libraries:

conda install selenium

How to install the Python Chromedriver Binary

If you try to install the python-chromedriver-binary with:

It will most likely fail with this error message:

What the error we saw means, is that conda was not able to find the python-chromedriver-binary in the default channel. 

For this reason, we have to look for this python library from an alternative source. In our case the alternative source is the conda-forge, a community-led collection of distributions for the conda package manager.

Let’s try to install again, but this time providing the conda-forge channel.

How to install The Pandas and BeautifulSoup Library

We install Pandas and BeautifulSoup as we are likely to need them:

Resources – Web Scraping Videos + Source Code

Source Code:https://github.com/armindocachada/yeelight-nvidia-rtx-ryzen-stock-checker


Source Code:https://gist.github.com/armindocachada/e54309743734e091a7b849d66c5fc390

Source Code:https://github.com/armindocachada/yeelight-nvidia-rtx-ryzen-stock-checker/blob/main/Buy%20Bot%20-%20RTX%20GPU.ipynb

Source Code:Amazon Price Scraper with WhatsApp Notifications (github.com)

While trying to create a Python Bot you might face a variety of errors, watch this video:

Sours: https://spltech.co.uk/how-to-make-a-python-bot/

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 DO

First 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-Requisites

For this tutorial I’m going to be using Python3, 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:

  • Python3
  • A fauna account
  • A cloudinary account

Preparing the database

The 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.

Alt Text

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 Collections

Next, 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:

Alt Text

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.

Alt Text

Let’s move on to creating indexes for easy retrieval of information from our database.

Creating Indexes

For 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:

Alt Text

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:

Alt Text

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_KEY

One 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 BotFather

To 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.

Alt Text

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.

Alt Text

Scripting Telegram-Business

We'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:


Next, 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.

A screenshot of the terminal showing the commands used to activate the virtual environment as well as the one for installing the listed out packages.

We’ll start by creating the following files in our project folder:

  • handlers.py
  • main.py
  • config.py
  • .env

I’ll split the implementation of the handlers into two parts :

  • Customer Functionalities
  • Business Functionalities

We’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:

Once 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.

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.

We’ll add some of the boilerplate config for some of our dependencies, so add the following after importing all these:

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 Methods

We’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.

Look 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:

This 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.

However, 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:

At 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:

Save this,go to your terminal, and run the bot via the main.py file as follows:

A screenshot showing the command to run the file from the terminal

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:

A screenshot showing the response from our bot (telegram-business) as we've programmed it from earlier steps

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.

A screenshot showing the response from our bot  after we provide it with the details it asked for.

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.

A screesnshot of another response from the bot prompting the user to enter details about his/her business just as we've programmed it.

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.

  • Adding 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.

This 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.
  • View 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.

This 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.

Testing The Bot

We 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:

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.

A screenshot of the response from the telegram bot

A screenshot showing what the bot sends to the business owner when a new order is placed.

The second image shows what the business owner sees each time a customer places an order.

Conclusion

In 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.

Sours: https://dev.to/curiouspaul1/building-an-e-commerce-telegram-bot-using-python-and-fauna-1hj5
  1. Logitech harmony elite remote only
  2. Hvac technician salary payscale
  3. Fundations kindergarten pacing guide

When I created my first bot with Selenium library – I could not believe how easy and intuitively Selenium is. It’s like writing a scenario for a movie – You just describing step by step what should be going on. In my particular case – Selenium helped me to automate reporting of some advertising platforms, where I had no access to an API. But also can be used for web scraping, automation, etc.

I wrote a simple bot which sends me an email from my web page contact form as an example. This is how it works:

How to create your own bot

In order to lunch your bot you should have a special simple web browser app – the most popular are ChromeDriver (equivalent of Chrome) and GeckoDriver (equivalent of Mozilla Firefox). I’ll use ChromeDriver in this tutorial. So at first – go to official ChromeDriver page and download it:
https://chromedriver.chromium.org/downloads

Remember – You should have the same version of ChromeDriver as your normal Chrome browser installed on your computer, you can check it by typing this: chrome://settings/help
Next – install the Selenium library using pip as usual:

Next – try to run the code below after replacing ‘/path_to_chromedriver/chromedriver’ with full path to chromedriver.exe on your computer:

This script should do all the stuff you have seen in the example at beginning of this article. Waiting (time.sleep(x)) is necessary to give the page time to load, values inside – seconds.
With Selenium You can do almost anything what comes to your mind: clicking buttons, filling forms, downloading files, making screenshots and so on. While writing a script for Selenium bot – You should think about it like you’re writing a very detailed instruction for a human.

Of course you should tell Selenium somehow which particular element on page you want to interact with. You can use different methods for that: find element by it’s id, class, css selector, or even find an element which contains a specific text. There you can find the full specification:
https://selenium-python.readthedocs.io/locating-elements.html

Below You can find some popular commands:
This will click the first element (could be a button for example) which contains “download” text:

This command will find form with “type=’search'” attribute and fill it with “hello” string:

This is how you can make a screenshot of page:

Also You can run Selenium in “headless mode” – it means that the script will be running in background. You will not see how it’s working but still you will have the results of it’s work. There is an example which opens Google News and makes a screenshot of the page:

Thanks to this mode You can run script on a server, I prefer using Google Cloud VM for that purposes.
Hope this article will help You to start your journey with Selenium and it will help You to automate some boring or repeatable suff. Cheers!

Sours: https://serhiipuzyrov.com/2019/12/how-you-can-create-your-own-bot-using-selenium-webdriver-and-python/
How to make an Auto-Buying Bot using Selenium (IN 20 MINUTES) (DEPRECIATED)

Python Selenium Tutorial 2021

Want to be able to magically make bots that do your work for you? In this tutorial, I’ll show you how to use Selenium Webdriver to automate tasks, use it for testing applications, and also go into some lesser-known advanced features available with Selenium Webdriver

Selenium is a tool designed for automating web browsers programmatically. Selenium’s primary use is for automated software testing but it is also commonly used for scraping content where rendering Javascript is necessary and any other activity requiring automation in the browser such as bots.

One of the main selling points of Selenium is that it supports nearly all popular browsers such as Chrome, Firefox, Safari, Internet Explorer, and others. All of this is accessible through a uniform API that can be used with almost any programming language. In this tutorial, you’ll be using Python but you could also slightly modify the code to be used in Javascript, C#, Java, PHP, and other languages.

If you prefer watching a video you can follow along here:

To follow this tutorial you need 2 things:

  • A basic Python development environment
  • Google Chrome and Chromedriver downloaded

You can download the chrome driver at this link:

Make sure to get the version that matches your current browser version for Chrome. If you use Firefox you can also get geckodriver to use Selenium.

Place the chromedriver.exe file in your project directory and Selenium will automatically find it

The first thing you need to do is install the Selenium Python client library using pip:

You can verify everything is working properly by running the following code

This code will import Selenium’s webdriver module, open up a Chrome instance, visit Google’s homepage, and then close.

You probably want to do more with Selenium than just open up websites. To do that you’ll need to interact with elements on web pages to automate whatever task you would do normally.

Luckily, Selenium provides several different ways to find elements on web pages and interact with them.

When automating any task with Selenium there are 2 things you need to do:

  1. Find the element using a locator tag
  2. Use a built-in method or property to interact with that element

There are many ways to accomplish the same goal with Selenium. In this section, I will give you an opinionated way based on my own experience of how you should locate web page elements with Selenium.

For example, you could grab the search bar element on Google’s home page using any of the following lines of code:

Order of priority for selectors

As you can see from the code above, it’s much easier to use something like a name or ID tag than to use Xpath or alternative search options. Whenever possible you’ll want to use those much simpler available options, but in some cases, you won’t have a choice.

My personal order for finding elements is:

  1. Name or ID tag
  2. CSS classes
  3. CSS selectors
  4. Xpath
  5. HTML tag names

Most websites will be easy to scrape or interact with and you’ll be able to use simple CSS classes or IDs. Other websites will actively try to prevent scraping and you’ll have to use more complicated selectors to find elements on the page.

Reddit is a good example of this, it’s one of the more challenging websites to scrape, so after this tutorial you’ll be able to handle most other websites very easily in comparison!

Returning multiple elements

The code above will only return the first instance that matches the parameters of the search. If you want to return an entire list of elements, for example, a list of tweets or some other content, you can simply add an “s” to the method call like this:

This code will return every web element that matches in an array that you can then iterate over.

Finding nested elements

You also have the option of using a parent element to search for more elements inside. Instead of searching from the driver object, you can first locate an element on the page, and then run further commands to locate inner elements.

Using dev tools to speed up Selenium development time

Here’s a selenium veteran tip. When I first started out working with Selenium it took forever for me to find elements. I would change my python selector code, run the entire program, and often it would cause an error when it couldn’t find an element. This was frustrating because for long-running bots testing each small change could take a few minutes.

It took me way too long to realize that I could use developer tools to speed up the iteration process. Any selector you use in Selenium can first be tested in your dev tools console to make sure you find the elements you want.

You won’t need to do this for basic stuff like CSS class names or IDs, but when working with complicated queries using Xpath it’s a lifesaver that will save you hours. Here’s an example of how to use Xpath with chrome dev tools to save an element using the command:

Interacting with web elements using Selenium

So now you know how to locate elements with Selenium, now let’s learn how to actually do something with them.

Each element has a number of built-in methods to easily interact with them, here are the most common ones:

In addition to actions you can take on web page elements, there are also numerous properties you can access for each element to get more information if you need it. Be sure to check out the documentation and API to see all the options available

Sours: https://codeburst.io/python-selenium-tutorial-2021-57162fa620ac

Bot python shopping

BSCTokenSniper v1.0

A bot written in Python to automatically buy tokens on the Binance Smart Chain as soon as liquidity is provided.

BSCTokenSniper is a bot written in Python to detect new PairCreated events in the Binance Smart Chain (when a liquidity pair has been created) and buy the token. It is quite reliable and works well but it is the first version, so if you find any problems/improvements/suggestions please let me know by raising an issue.

Description

The aim of BSC Token Sniper is to buy new tokens with a specified amount of BNB, with the aim of the price rising Once the bot detects a PairCreated event, it is able to check the token (mini audit).

It can check if:

  • Source code is verified.
  • If valid PancakeSwap v2 router is being used
  • If a mint function exists
  • If it is a potential honeypot
  • PancakeSwap v1 router address is not being used.

The user can decide whether to enable the mini audit or turn it off (bear in mind you will likely be investing in a lot of scams if you don’t). Once the token has/hasn't been through a mini audit the bot will then attempt to buy X amount of tokens with the specified amount of BNB. The bot will buy the tokens directly through the Binance Smart Chain using the PancakeSwap v2 router and factory address, so it is much quicker than the PancakeSwap web interface.

By avoiding web interfaces & Metamask and directly with Ethereum & EVM Nodes you can snipe tokens faster than any of the web-based platforms. This allows tokens to be sniped almost instantly. During our testing we found the bot would typically be within the first 3 buy transactions of all tokens it finds. The bot buys the tokens using the user's wallet address and private key. This information is kept secure, is only stored locally on your computer, and is only ever used to buy tokens (look through the code to see for yourself).

The bot does not incur any additional fees, only fees are BSC network transaction fees and PancakeSwap fees.

Prerequisites

  • Python 3 or later installed
  • Node.js installed (easiest way) – Install windows version from https://nodejs.org/en/download/
  • Web3 installed (in windows command line type: npm install Web3)
  • BscScan API key (completely free of charge, create an account on BscScan and generate a free API key)
  • BSC wallet address and private key
  • enough BNB in your wallet to snipe tokens.

Setup

  1. Install all dependencies (above)
  2. Edit config.json file with your wallet address, private key and BscScan API key.
  3. (Optional) if you are in windows, open the command prompt and right-click the title bar, click ‘properties’ and set screen buffer size height to 2500. This allows you to scroll through the history of your token snipes.
  4. In command prompt (assuming you are using windows) type 'python' and press enter, and check that it is recognized by the computer. If you get a message that says it isn't recognized, then change the 'launchBSCTokenSniper.bat' file and replace 'python' with the path to your python program's executable file (make sure the filepath is in "" quotes).
  5. Run ‘launchBSCTokenSniper.bat’ and you’re good to go!

Configuration File

When you download the bot, you will find a config.json file. This is where you need to add the following data.

walletAddress: your BSC wallet address (e.g., Metamask) walletPrivateKey: your private key of your wallet address (your private key is kept safe and not shared in any other place) amountToSpendPerSnipe: The amount in BNB you want your wallet to spend on every new token. (e.g., 0.00025 means a new snipe will spend 0.00025 BNB on the new token) transactionRevertTimeSeconds: Time to spend before transaction reverts. Recommended to leave at default. gasAmount: amount of max gas to use per transaction. Recommended to leave at default. gasPrice: max price of gas to use per transaction. Recommended to leave at default. bscScanAPIKey: Your API key from BscScan. observeOnly: enabling this will disable buying of coins but allows you to observe how the bot audits tokens. Recommended to try this at the start to make sure the bot can scan for new tokens.

Mini audit

The bot has an optional mini audit feature which aims to filter some of the scam coins (eg. wrongly configured, honeypots). Obviously, this is not going to be as good as a proper audit (eg. CertiK) but at least the coins the bot will buy will be higher quality and if you enable the options, you should be able to sell the tokens later on (provided it hasn’t been rugged).

The following json entries are for mini audit. Set all to false to disable mini audits, although beware you will probably be buying a lot of scam coins. checkSourceCode: checks if source code is verified. This function is needed for all the other functions so if you disable this be sure to disable all the other audit options. Recommended.

checkValidPancakeV2: checks if the correct PancakeSwap v2 router address is used in the code. Be aware some contracts may externally set their router address so this function may reject a potentially good token. Not recommended.

checkMintFunction: checks if a mint function is present in the code. Recommended.

checkHoneypot: checks the code to see if it might be a honeypot (where you can buy tokens but cannot sell). Recommended.

checkPancakeV1Router: checks to see if the PancakeSwap v1 router address is used in the code. You will not be able to sell the tokens later on if PCS v1 router address is used. Highly recommended.

Note: be very careful when editing config.json and make sure to not alter the syntax. For mini audit options, either use “True” or “False” making sure to capitalise the 1st letter. Any other spelling will not work.

Things to note

  • Do not worry if you are not seeing any new tokens being detected. There are often around 10-20 new tokens being created per minute but that can vary quite a lot. Sometimes no new tokens may be detected for a few minutes.
  • The bot only buys tokens whose liquidity is paired with Wrapped BNB (WBNB). You could alter the code to buy tokens paired with another currency if you wanted.
  • Please check that you have enough BNB in your wallet to afford sniping new tokens. If you don’t the bot will not work.
  • Please be careful when editing the config.json file. If you delete a comma or quotation mark etc. the bot will not work and throw an error.
  • To launch the bot, run the ‘launchBSCTokenSniper.bat’. The bot should then open in a cmd window and load.
  • Don’t left click in the cmd window as it will enable select mode and stop the output (you will see ‘Select’ in the title). If this happens right click your mouse to deselect it.

FAQs

I've sniped loads of coins - but how can I check which ones have made a profit?

  • For this go to poocoin.app, click 'Wallet' and connect your Web3 wallet that you are using for your bot (eg. Metamask).
  • It will then give you the list of tokens in your wallet and show you which ones have made the highest profit.
  • Click the descending arrow next to the balance tab to show highest to lowest tokens value.
  • Then you can manually sell the tokens which have made you a profit on PancakeSwap.

I keep getting ‘Transaction failed’ – what’s going on? Either:

  • Gas amount / price too low
  • Wallet address / private key incorrect
  • Not enough BNB to pay for the token and TX fees

The bot isn’t sniping that fast (eg. couple seconds between detection and buying)

  • This is mainly due to internet speed and computer processing power.

Risks:

Investing in BSC tokens / shitcoins is risky and be aware you could lose all your money. For this reason, do not invest more money than you are prepared to lose. It is pretty much impossible to snipe bots very early and be sure it isn’t a rug pull. When people create tokens in most situations, they will manually create liquidity in PancakeSwap. This is when the bot will detect the token. If they burn / lock liquidity, they will then usually send their LP tokens manually to a deadcoin address or put them in a liquidity locker. Therefore, you can’t immediately snipe the tokens with 100% certainty they aren’t rugpulls.

The mini audit feature can’t be 100% accurate but aims to filter out the majority of scams / hacks and reduce the chance of losing your money. If a programmer creates token code in a unique way, they may be able to bypass detection although this is generally quite rare, as the majority of tokens are forks of big projects with very little of the code having been changed e.g., Safemoon.

Things to do / improve / bug fixes / thoughts:

  • Clarify installation of web3 as alot of users had issues with it
  • Improve honeypot detection (at the moment it is very simple and some tokens are rewriting their code to bypass the bot's detection) (bscheck.eu seem to do a good job of detecting honeypots better than the bot can do, will try to contact them and see how their detection algorithm works)
  • Improve reliability (occasionally it can freeze)
  • Use WebsocketProvider instead of HTTPProvider (faster so will snipe tokens quicker)
  • Implement a feature that makes the bot only invest in tokens that have a certain amount of liquidity (ie. only invest in tokens that have min. 10 BNB liquidity)
  • Implement a GUI? Maybe
  • Look into rugpull detection
  • Auto sell after certain profit reached?
  • Make ETHTokenSniper that does the exact same but runs on the ethereum blockchain
  • Make code more efficient so can run faster and snipe faster
  • Are all tokens that haven't verified their source code bad? Probably not. But I'm currently just assuming that developers will verify their source code before adding liquidity.

GitHub

https://github.com/BytePhoenixData/BSCTokenSniper

BotCryptocurrencyAutomation

Sours: https://pythonawesome.com/a-bot-written-in-python-to-automatically-buy-tokens-on-the-binance-smart-chain/
I Coded A Checkout Bot To Buy High Demand Products in Seconds!

How to code a Telegram Bot to get stock price updates in pure Python

Without further ado, let’s get started!

First off, we will need an API to get the price changes for our stocks we have in mind. For simplicity, we will be using the yfinance, a library that is maintained after the Yahoo! Finance API was decommissioned. Its API is written in Python and we will also be using a Python-based library for the Telegram API known as python-telegram-bot.

We will first create a simple script based on the yfinance API to obtain price movements for an input ticker. Next, we will setup the Telegram handler to listen for requests made to the bot.

Step 1: Create a script to obtain price changes using yfinance

The script below takes in a ticker as input, with a lookback period as an optional argument, and returns a Tuple consisting of the percentage change in the first index and the list of closing values that contribute to the percentage change (mainly for extracting the exact prices if necessary) in the second.

Step 2: Create a telegram bot with Botfather

Follow the instructions on the bot to setup your bot (yes, you’re using a bot to create a bot —i.e., bot-ception). At the end of it, you’ll be given a bot token that is required to access the HTTP API. Take note of this token. We will use this in the next step.

Step 3: Export this token as an environment variable so our app can use it later.

From the command line, run:

export TELEGRAM_BOT_TOKEN=<YOUR_BOT_TOKEN_HERE>

Step 4: Create an that is our Telegram bot

This telegram bot only has a single command — get_px_change — which is initiated using the command. On telegram, to get the price change for the AMZN ticker, run after serving the app locally via .

Step 5: Register this command on Telegram so that it is more intuitive for users to know that this command exists

Go back to BotFather to register this command get_px_change via . It might also be worth including a command like start to inform users how to use your bot.

FYI: Command handlers start with and appear in the command list.

Note: Instead of command handlers, a conversation handler can also be used in conjunction with a keyboard markup (as seen in the above GIF). The latter may be more intuitive and convenient for users to navigate around.

More notes: It is best practice to have error handlers to handle unidentified commands.

Step 6: Place the scripts on a GitHub repository for easy deployment on Heroku

However, before we can deploy on Heroku, we need to define our environment. To do so, we need two new files:

a) Procfile — this tells Heroku the type of application and also the command to run after setting up the environment. It will consist of only this line:

web: python -m telegram_bot_app

b) requirements.txt — this defines the environment requirements of a typical Python-based application. It should look something like this:

pandas==1.0.1
numpy==1.18.1
yfinance==0.1.54
python-telegram-bot==13.1

The folder structure should look like this:

.
├── telegram_bot_app.py
├── ticker.py
├── Procfile
└── requirements.txt

Push these files to a GitHub repository on the main/master branch.

Step 7: Deploy this app on Heroku

If you don’t have an account with Heroku, create one and also install the Heroku command line interface (CLI).

a) Next, create a new project via the CLI:

heroku create <project_name>

b) Set the telegram bot token as an environment variable.

heroku config:set TELEGRAM_BOT_TOKEN=<YOUR_BOT_TOKEN_HERE>

c) Modify your to listen to webhook events.

d) Push your GitHub repo to the Heroku remote. Note that Heroku will only build if you push to the main or master branch. From your git repo, run the following:

git push heroku master
Sours: https://levelup.gitconnected.com/how-to-code-a-telegram-bot-to-get-stock-price-updates-in-pure-python-c35d3c44b04c

Now discussing:

Building a Sniping Bot with Python (in the name of automated testing?)

11 minute read

So my brother-in-law has been bugging me lately. To our dismay, he has become a fan of Supreme products. Ever since, he has been complaining how hard it is for anyone to get his or her hands on some of the most coveted items - more often than not, the only way for ordinary people to get them is through reselling sites, at a huge premium.

After a little research, it became obvious that those who are able to get the items upon release, are most likely using bots. What are these so-called bots? It is nothing more than a carefully written script, written to automate and optimize the purchasing process, and to be among the first to get to the checkout line (online). Sounds interesting? Let’s see how we can write up a simple script for exactly that purposes.

This post is purely for educational purposes - please be advised to follow the Terms of Services of each website you visit.

Those paid bots are probably much more sophisticated - this is just an illustration.

What is Selenium?

Selenium Logo

Selenium is an open-source web-based automation tool often used for automated testing of web applications. It is often paired with Python, since, why not? In some sense, the sniping bot we will be building is also a form of automated testing: Supreme may very well write up the same script, and run it after every new deployment of their web app. If the purchase goes through, awesome, at least the checkout process is not catastrophically buggy! The beauty of such scripts is that you can write them to test all aspects of your web app, and hence whenever you update your codebase, all you need to do is to run the tests and wait for the results, rather than frantically clicking through your web app like a maniac.

Set up

There is little prerequisite here. Aside from installing the relevant packages, one extra step is to download and setup the actual driver for your choice of browser. More detailed instructions can be found here. Once you open the link, scroll down to the “Drivers” section, which would walk you through the process. For my example, I will use the Firefox driver.

Goal

For our example, let’s define our goal as follows:

  1. Given a product name, we search through the listings on and determine if it exists;
  2. If it does, we navigate to the product detail page, and check if it is available;
  3. If it is available, add it to our cart;
  4. Checkout with pre-configured payment information.
  5. Profit.

To summary: enter a product name, then … profit*!

* Through the mental satisfaction of writing a piece of code that actually runs!

Detailed Steps

0. Laying the Groundwork

Here we import the libaries we plan to use, and set the we will be running our script on. is a local file I use to store some more sensitive info (for example, payment methods), which I can exclude from any versioning software (github). You may have noticed that aside from selenium, I’ve also imported . This is a more light weight library we can use to do some preliminary probing, when we don’t need to perform too complicated operations. In fact, a separate library might be able to cover our preliminary needs, but whatever.

1. Get links to all products

Here, we build up the url leading to the page that hosts all products, start an HTMLSession, send and process a request, which is returned to the variable . Now we have the code of the webpage, what next? A common trick is to use the inspection / developer tool on most browsers, either by pressing , or right-clicking and select .

Supreme List

For example, here we can see that all the products are wrapped in an (unordered list) element, with an of “shop-scroller”. Within this wrapper, each product consists of (list item) and a nested tag holding the link to the product details page. Now if we look back onto our code snippet, it looks at the returned , looks at the code of it, locates the first (and probably only) element with id of “shop-scroller”, then finds all elements within.

2. Check for matched product

We first process our input product name (the name we want to match against) into a list of lowercase words. Then we invoke the function we’ve defined above, which will hand us over the list of elements. Now we will loop over the list: for each item in the list, we find the tag element and access its attribute. Recall from the screenshot above, that that shall give us the link to the product details page.

Now holds our desired url. We use the same method as above to check out that link:

Supreme Detail

By inspecting the source code, we discovered that the selector would help us locate the product name. We convert that to lowercase as well, then iterate through our target list: if all words in our search target are contained in the official product name, we say that we have found a match. If a match is found, we will continue go check if it is still available.

3. Check if product available

Super straightforward - we pass in the same we have used to figure out the product name, but this time we look for an element with . We have arrived at this identifier through inspecting various product pages - check out some that are available, some that are sold out, and try to figure out what element’s existence can tell you the product is still available.

4. Perform the purchase

Now that we have got the list of returned from step 2 above, we will focus on purchasing whatever product that is on this/these urls.

This step is easier to perform through Selenium, since we will be clicking buttons, and filling out forms, all of which are quite easy with Selenium. The logic is still pretty much the same as using - we still need to find the elements we are interested in. Here, we first initiate the web driver, navigate to the product details page, and look for an element within an element with id “add-remove-buttons”. If it’s not there - too bad, we were probably too slow and the product is no longer available.

If it is there, we want to click on it to add to our cart. How do we do it? Well… we simply call the method on the found element. We added a 1 second pause to mimic human behavior - which is probably in vain as we will see later. Now that it is added into our shopping cart, we can navigate to the checkout page. Then we fill in all the info they ask for - again, please be careful with your sensitive info, and only keep it on safe and private locations.

We needed to click on a few checkboxes that are somehow covered by a different element. Selenium conplained, so we had to click on the covering elements instead.

When all info is filled in, we just look for the pay button, and perform another , as simple as that!

Wrapping it Up

For ease of usage, we might want to wrap the codes into a function, which we could call from outside of Python shell.

And to use it, simply run this from command line (where is what I named my script):

Notes

  1. If we are actually trying to snipe a product from release, we may want to check availability at a fairly high frequency leading up to the release time, so we can purchase the item as soon as it is released;
  2. There are tools to deal with this, but for now, we can solve the challenge manually - still a lot faster than finding the product, adding it to cart, filling in the info, etc. right?

Resources

Demo

Tags: bot, selenium

Categories: Tools and Infrastructures

Updated:

Share on

Twitter Facebook LinkedIn
Sours: http://www.michaelfxu.com/tools%20and%20infrastructures/building-a-sniping-bot/


982 983 984 985 986