I want to enable the script to change my Discord username, I was looking on the Internet but I did not find anything. I would also like the script to change the avatar, please help in advance, thank you in advance.
I want it to work like my status change script I will post here but I want it to change username \ avatar
class main:
def __init__(self, token, status):
self.token = token
self.status = status
string = self.status
print("[+] Succes Status Set " + string)
self.set_status(string)
def set_status(self, status):
requests.patch("https://discord.com/api/v9/users/#me/settings", headers={"authorization": self.token,"content-type": "application/json"}, data=json.dumps({"custom_status":{"text":status,"emoji_name":"👉"}}))
if __name__ == "__main__":
if requests.patch("https://discord.com/api/v9/users/#me", headers={"authorization": token,"content-type": "application/json"}).status_code == 400:
main(token, status)
else:
print("Failed to connect to token")
input()
Related
How can I get response from Telegram bot and get some information to answer from local file? I wrote code below, but part with current_status doesn't work.
Could you please tell me why it doesn't work?
import telebot
import requests
url = "https://link.com"
bot = telebot.TeleBot('TOKEN')
#bot.message_handler(content_types=['text'])
def get_text_messages(message):
if message.text == "Status" or "status":
bot.send_message(message.from_user.id, curl_request())
def current_status():
with open('current_status.log') as file:
status = str(file.readline())
return status
def curl_request():
resp = requests.get(url)
if resp.status_code == 200:
return("Available \n", current_status())
else:
return("Isn't available \n", current_status())
bot.polling(none_stop=True, interval=0)
I mean, I getting answer from bot in Telegram just Available or Isn't available without text from my file which I open in current_status function.
bot.send_message() takes text as its second parameter, but your function curl_request() returns tuple.
Can you try make it return "Available \n" + current_status()?
I am trying to create a Twitter bot using Tweepy that replies to mentions but needs to process the tweet the mention is replying to. I have everything else figured out except how to get the tweet the mention is replying to. I have looked through the documentation several times and have been unable to find a way to do this. Any help is much appreciated.
to have your bot reply to a user's screen_name is what I think is what you are asking here. You need to have:
class MyStreamListener(tweepy.StreamListener)
inside the class, function on_status(self, status) and on_error(self, status_code)
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
name = status.user.screen_name
id_str = status.id_str
message = " // < message > //"
reply_tweet = "#" + str(name) + " " + message
api.update_status(reply_tweet, in_reply_to_status_id= id_str)
print(" <tweet received> " + status.text)
print(" tweet sent back > " + reply_tweet)
def on_error(self, status_code):
if status_code == 420:
print("rate limit reached")
return False
i would suggest having a timer in a while loop function as to avoid rate limits
What I am trying to achieve is that the user will first ask the bot a question. Let say the user wants to find the nearest money changer he/she will type "I need to find a money changer. Then the bot will reply with 'Please provide the location". Once the user provides the coordinates the bot will then reply with all the nearby locations money changer.
from flask import Flask, request
import requests
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
#app.route('/sms', methods=['POST'])
def bot():
incoming_msg = request.values.get('Body', '').lower()
resp = MessagingResponse()
msg = resp.message()
if 'moneychanger' in incoming_msg:
search1 = 'Please provide the location please'
msg.body(search1)
message_latitude = request.values.get('Latitude', None)
message_longitude = request.values.get('Longitude', None)
responded = True
if message_latitude == None:
location = '%20' + message_latitude + '%2C' + message_longitude
responded = False
url = f'https://tih-api.stb.gov.sg/money-changer/v1?location={location}&radius=2000'
r = requests.get(url)
if r.status_code == 200:
data = r.json()
search = data['data'][0]['name']
else:
search = 'I could not retrieve a quote at this time, sorry.'
msg.body(search)
responded = True
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
Twilio developer evangelist here.
I believe you are working with the Twilio API for WhatsApp, based on your using location parameters.
The issue here is that you are trying to reply to and receive more information within the same webhook request. However, the text message (with "moneychanger" in it) will come in a different request to the request with the location message. So, you need to store some state within your application that says your user is currently looking for a moneychanger.
Here's an example using Flask Sessions to store the incoming message and then ask for location and if there's a message put that together with the message and respond:
from flask import Flask, request, session
import requests
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
# Don't use these bytes because they are in the documentation.
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
#app.route('/sms', methods=['POST'])
def bot():
incoming_msg = request.values.get('Body', '').lower()
resp = MessagingResponse()
msg = resp.message()
message_latitude = request.values.get('Latitude', None)
message_longitude = request.values.get('Longitude', None)
if 'moneychanger' in incoming_msg:
# We're looking for a moneychanger, ask for the location
response = 'Please provide the location please'
session['message'] = incoming_msg
elif message_latitude && message_longitude && 'message' in session && 'moneychanger' in session['message']
# We have the location and the previous message was asking for a
# moneychanger.
location = '%20' + message_latitude + '%2C' + message_longitude
url = f'https://tih-api.stb.gov.sg/money-changer/v1?location={location}&radius=2000'
r = requests.get(url)
if r.status_code == 200:
data = r.json()
response = data['data'][0]['name']
else:
response = 'I could not retrieve a quote at this time, sorry.'
# we're done with the original message so we can unset it now.
session['message'] = None
else:
# In this case, either you have a message that doesn't include
# 'moneychanger' or you have latitude and longitude in the request but
# no session['message']. You probably want to do something else here, but
# I don't know what yet.
response = 'I\'m not sure what you\'re looking for.'
msg.body(response)
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
You may also want to extend this so that if you receive a message with location in before receiving the request ('moneychanger') then you could store the location in the session and then ask what the user is looking for.
Let me know if that helps at all.
How does post call work with LOcustIO? I was suspecting Locust not doing what it is suppose to do because it was returning success for all load testing I was running so I decided to post, write to the DB via a web application using LocustIO, to my surprise nothing was written to the db. Though I know some have successfully done this, so I want to know how to write to the Db using LocustIO as part of my load testing.
This is the code used:
from locust import HttpLocust, TaskSet, task
import logging, sys
from credentials import *
class LoginWithUniqueUsersSteps(TaskSet):
institutionCode = "NOT_FOUND"
username = "NOT_FOUND"
password = "NOT_FOUND"
def on_start(self):
if len(USER_CREDENTIALS) > 0:
self.institutionCode, self.username, self.password = USER_CREDENTIALS.pop()
#task
def login(self):
self.client.post("/dejavuweb/", {
'institutionCode': self.institutionCode, 'email': self.username, 'password': self.password
})
logging.info('Login with %s institutionCode %s username and %s password', self.institutionCode, self.username, self.password)
#task
def createTerminal(self):
response = self.client.request(method="POST", url="/dejavuweb/Home#Function/7", data= {"TerminalName": "RealterminalName"})
print("Create; Response status code:", response.status_code)
print("Create; Response content:", response.content)
class LoginWithUniqueUsersTest(HttpLocust):
task_set = LoginWithUniqueUsersSteps
host = "http://dev.trublend.cloud"
sock = None
def __init__(self):
super(LoginWithUniqueUsersTest, self).__init__()
Mind you, I copied, edited the code snippet above to achieve what I want.
Screenshot of LocustIO result:
I have a working python/tk program that runs a cgi script based on user selection. I'm working to cut this down to a small script that just focuses on one particular cgi script. It appears to be getting the session id correctly but when I launch the browser I keep getting "access denied". As the other program works I not expecting any issues from the website. Any help will be appreciated.
UPDATE:
If I use a debugger and set a breakpoint on the line print url the url printed in the console, as seen below, does work. I now know the session id token is good.
Also if I step into the webbrowser function and then step over after that the script also works.
Here is my code.
import json
import tornado.web
import tornado.websocket
from tornado import gen
import tornado.ioloop
import webbrowser
from struct import *
request_id = 71
ip_address = "10.22.4.14"
# ************************************************
# Procedure to open websocket and get session id
# ***********************************************
#gen.coroutine
def open_ws(ip, username, password):
global client
global request_id
global session_id
ws_url = "ws://" + ip + ":7011/"
try:
client = yield tornado.websocket.websocket_connect(ws_url, None, None, 5, None, None)
# print("websocket %s open" % ws_url)
except error:
exit()
# Send Mercury login request
JSON = '{"requests":[{"request_id": %s, "login":{"username": "%s","password": "%s"}}]}' % (str(request_id), username, password)
client.write_message(JSON)
results = yield client.read_message()
# print("msg is %s" % results)
# Parse the response of login request to get the error code
parsed_json = json.loads(results)
err_code = parsed_json['responses'][0]['request_response']['result']['err_code']
if 0 == err_code:
# Parse the response of get_command_result to get the session id
session_id = parsed_json['responses'][0]['request_response']['login']['session_id']
# print("login succeeded - session id: %s" % session_id)
else:
print("login failed")
# error_exit(err_code)
def get_token():
tornado.ioloop.IOLoop.instance().run_sync(lambda: open_ws(ip_address, 'admin', 'admin'))
return session_id
session_id = get_token()
print "Token is " + session_id
url = "http://" + ip_address + "/scripts/dostuff.cgi?session=" + session_id
print url # add breakpoint here
# launch browser
webbrowser.open(url)
Console output:
Token is 7zNSZX9liaUDFFN0ijn-LWQ8
http://10.222.4.14/scripts/dostuff.cgi?session=7zNSZX9liaUDFFN0ijn-LWQ8
Resolved. The script was ending therefore closing the socket before the browser had a chance to respond to the request