A Discord bot reference repo leveraging the newly rewritten
web3.py WebSocketProvider,
which includes eth_subscribe support. Check out the
blog post for an
introduction to WebSockets and the provider.
This bot can listen for subscriptions on a particular channel or execute one-off requests, like retrieving a balance or some block data.
The bot's architecture can support multiple chains. It will default to mainnet,
but you can add sepolia or optimism to the end of any command to interact
with those networks instead (if you include valid RPC URLs in your .env file).
One-off commands can be run in any channel that the bot has access to, for example:
!block latest sepolia- to return some data about the latest sepolia testnet block!balance shaq.eth- to return an ether balance (ENS supported)
The user flow for subscriptions is to:
- Tell the bot which channel to listen for messages in (
!listen) - Create a new subscription (
!newHeads, !transfers) - View your active subscriptions (
!subs) - Unsubscribe (
!cancel newHeads,!cancel transfers)
A couple of sample subscription commands are included:
-
!newHeadswill start a subscription watching for new block headers -
!transferswill watch for newTransferevents from the Art Blocks NFT contract
- Follow
discord.pydirections to create a bot account on Discord. By the end you'll have atoken. - Create your
.envfile to pass secrets into the app- Use the
.env.examplefile to reference the key names - Store your newly created
tokenasDISCORD_TOKEN - Add your websocket URL(s) to connect to a node
- Optional: include the channel ID of a channel you'd like to see startup messages in
- Use the
- Install dependencies:
pip install -r requirements.txt - Start the bot in a terminal:
python main.py - Use the bot. Try
!helpto view a list of commands. - Bonus: host your bot! You can only do so much from your local machine.
This bot is for educational purposes and does not aspire to be anything robustly production-grade. Hopefully it's a good starting point for your hackathon project or next adventure.