I am trying to use Solana Py to connect to serum's dex and get order book updates. I am not sure how to do this. I had something working using serum-vial, but I'm trying to rewrite that library because it has caused me too many issues.
As a proof of concept, I am trying to get "SOL/USDC" to load in. So I am trying to get SOL/USDC's account info to load in the proper program Id. Here is my code:
import asyncio
from asyncstdlib import enumerate
from solana.rpc.websocket_api import connect
from solana.publickey import PublicKey
from solana.rpc.async_api import AsyncClient
from solana.rpc.commitment import Confirmed
async def main():
client = AsyncClient("https://psytrbhymqlkfrhudd.dev.genesysgo.net:8889/", Confirmed)
print("Connecting...")
await client.is_connected()
response = await client.get_account_info(
PublicKey("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),
encoding="base64"
)
for stake in response['result']:
print(stake)
await client.close()
asyncio.run(main())
Related
as the title states, I'm writing a Slack Bot in Python and using NGROK to host it locally. I'm not super experienced with decorators, and I can get the bot posting messages in slack, however I can't seem to handle two events at once. For example, I want to handle a message and have the message keep repeating in slack until a thumbs up reaction is added to that message. The issue is I cannot figure out how to handle an event while another event is still running, please see the following code:
rom slack import WebClient
import os
import time
from pathlib import Path
from dotenv import load_dotenv
from flask import Flask
from slackeventsapi import SlackEventAdapter
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
app = Flask(__name__)
slack_event_adapter = SlackEventAdapter(
os.environ['SIGNING_SECRET'],'/slack/events',app)
client = WebClient(token=os.environ['SLACK_TOKEN'])
BOT_ID = client.api_call("auth.test")['user_id']
state = {}
#slack_event_adapter.on('message')
def handle_message(event_data):
message = event_data.get('event', {})
channel_id = message.get('channel')
user_id = message.get('user')
text = message.get('text')
messageid = message.get('ts')
state[messageid] = {"channel_id": channel_id, "user_id": user_id, "text": text}
if BOT_ID != user_id:
if text[0:12] == ":red_circle:":
time.sleep(5)
client.chat_postMessage(channel=channel_id, text=text)
if text[0:21] == ":large_yellow_circle:":
client.chat_postMessage(channel=channel_id, text="it's a yellow question!")
if text[0:14] == ":white_circle:":
client.chat_postMessage(channel=channel_id, text="it's a white question!")
#slack_event_adapter.on('reaction_added')
def reaction_added(event_data):
reaction = event_data.get('event',{})
emoji = reaction.get('reaction')
emoji_id = reaction.get('item',{}).get('ts')
emoji_channel_id = reaction.get('item',{}).get('channel')
client.chat_postMessage(channel=emoji_channel_id, text=emoji)
for message_id, message_data in state.items():
channel_id = message_data["channel_id"]
text = message_data["text"]
client.chat_postMessage(channel=channel_id, text=text)
print(message_id,message_data)
if __name__ == "__main__":
app.run(debug=True)
I can handle individual events, but I cannot handle them while another is running. Please help! :)
Flask is a synchronous web framework.
When it's running a view handler, it uses up a web worker thread. If you does something like time.sleep(...), that worker thread will still be occupied and unavailable to handle other requests until the sleep finishes.
There are a couple options you can do here.
You can use Bolt for Python, which is a Python Slack library that natively support asynchronous even processing. Instead of time.sleep(), you can do await asyncio.sleep(...), which returns the thread to the async loop, and allow the worker thread to process other events.
If you already have an existing slack application and don't want to rewrite your entire codebase to Bolt, then you'll need to handle the event processing yourself. You can do this by doing your work in an ThreadLoopExecutor, or by building your own async event Queue mechanism, or use Celery. Or if your slack bot has very low volume, you can probably just add more web workers, and hope for the best that you don't run out of workers.
I have been able to login to Telegram and send messages to myself and also retrieve users from a group. But whenever I try to add members to a group, I get an error.
Here is my code
from pyrogram import Client
import asyncio
from pyrogram.errors import FloodWait
TARGET = 'intendingcouples_class'
async def main():
app = Client("my_account")
users = []
async with app:
async for member in app.get_chat_members(TARGET):
users.append(member.user.id)
print(users)
await app.add_chat_members('myenki', member.user.id)
asyncio.run(main())
When I run the above code, I get this error
pyrogram.errors.exceptions.flood_420.FloodWait: Telegram says: [420 FLOOD_WAIT_X] - A wait of 73958 seconds is required (caused by "channels.InviteToChannel")
Please, how do I solve this problem?
Your error is clear:
pyrogram.errors.exceptions.flood_420.FloodWait: Telegram says: [420 FLOOD_WAIT_X] - A wait of 73958 seconds is required (caused by "channels.InviteToChannel")
You'll have to wait 73958 seconds to be able to use the method again. Besides that, adding members against their will to random groups can get both your group, and your account permanently banned.
I'm trying to write a simple script to close an opened session using Telethon lib:
from telethon import TelegramClient, events, sync
from telethon.sync import TelegramClient
from telethon import functions, types
import time
api_id = "YYYY"
api_hash = "XXXXX"
client = TelegramClient('#example', api_id, api_hash)
client.start()
#With this I can get all the necesary info about current sessions
result = client(functions.account.GetAuthorizationsRequest())
print(result.stringify())
#With this I should be able to close the sessions using it's hash:
result = client(functions.account.ResetAuthorizationRequest(hash=-123456789101112))
print(result)
But I get this error:
telethon.errors.rpcerrorlist.FreshResetAuthorisationForbiddenError:
The current session is too new and cannot be used to reset other
authorisations yet (caused by ResetAuthorizationRequest)
I initialized the session like 1h ago; I tried put some time.sleep before the ResetAuthorizationRequest, but that didn't did the trick. What should I do in order to close a session? Should I wait more? In that case, what's the aproximated time I need to wait?
I have a working WebRTC client, and I want to receive it's video via WebRTC using aiotrc (python). The other client is working fine as the recipient, we have tested it with a browser.
Using python, I configure the server, I create an offer with a Transceiver (I only want to receive the video), and I set the offer as the localDescription:
import json
import socketio
import asyncio
from asgiref.sync import async_to_sync
from aiortc import RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, RTCConfiguration, RTCIceServer, RTCIceGatherer, RTCRtpTransceiver
session_id = 'default'
sio = socketio.Client()
ice_server = RTCIceServer(urls='stun:stun.l.google.com:19302')
pc = RTCPeerConnection(configuration=RTCConfiguration(iceServers=[ice_server]))
pc.addTransceiver("video", direction="recvonly")
def connect():
sio.connect('https://192.168.10.123', namespaces=['/live'])
connect()
#async_to_sync
async def set_local_description():
await pc.setLocalDescription(await pc.createOffer())
print('Local description set to: ', pc.localDescription)
#send_signaling_message(json.dumps({'sdp':{'sdp': pc.localDescription.sdp, 'type':pc.localDescription.type}}))
set_local_description()
(Where the socket.io is connecting is a fake address in this case). After this point, I have no idea how to gather the ice candidates. I have tried using the iceGatherer with no luck:
ice_gath = RTCIceGatherer(iceServers=[ice_server])
candidates = ice_gath.getLocalCandidates()
I have to send the ice candidate to the recipient. At this point I couldn't find any information about, how to get the ice candidates using aiortc. What is the next step?
The code you posted has in fact already performed the ICE candidate gathering, when you called setLocalDescription. Look at the session description you are printing and you should see candidates marked as srflx which means "server reflexive": these are your IP addresses as seen from the STUN server's perspective, e.g:
a=candidate:5dd630545cbb8dd4f09c40b43b0f2db4 1 udp 1694498815 PUBLIC.IP.ADDRESS.HERE 42162 typ srflx raddr 192.168.1.44 rport 42162
Also note that by default aiortc already uses Google's STUN server, so here is an even more reduced version of your example:
import asyncio
from aiortc import RTCPeerConnection
async def dump_local_description():
pc = RTCPeerConnection()
pc.addTransceiver("video", direction="recvonly")
await pc.setLocalDescription(await pc.createOffer())
print(pc.localDescription.sdp)
loop = asyncio.get_event_loop()
loop.run_until_complete(dump_local_description())
Trying to build a Telegram Quiz Bot using pyTelegramBotAPI. I'm using sched to schedule the message Handler but i don't know how to stop the Message Handler and return to my Main Script which will scheudle the next Round.
Tryed to use timeout but it is not working!
My Code:
import telebot
import sched, time
def listen():
print("Send my your Answer")
#bot.message_handler(func=lambda message: True, content_types=['text'])
def command_default(m):
print(m.text)
bot.polling()
API_TOKEN = 'xxxx'
s = sched.scheduler(time.time, time.sleep)
bot = telebot.TeleBot(API_TOKEN)
s.enter(50, 1, listen)
s.run()
In this use case you have to use something called a Finite State Machine (FSM). You keep track of user states, such as one where the user is ready to send an answer.
This is already implemented in pyTelegramBotAPI, with the next_step_handler(). However, I suggest you instead create your own solution, as the one provided by the wrapper is quite buggy.
Here is an example (you can translate the page): https://groosha.gitbooks.io/telegram-bot-lessons/content/chapter11.html