(first post sorry if i do this wrong) So I am making a bot (on discord) for me and my friends using discord.py (since python is the easiest code ever) and I've came across this. I need to get values from keys INSIDE OTHER keys. How do I do this?
So I've tried to change res to res.text and res.json and res.content and I could only find the "data" but not "id","name" or "description" which I need.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import requests, json
import asyncio
Client = discord.Client()
client = commands.Bot(command_prefix='?')
#client.event
async def on_ready():
print('started')
#client.command()
async def findfriends(ctx,userid):
res = requests.get("https://friends.roblox.com/v1/users/"+userid+"/friends")
var = json.loads(res.text)
def a(a):
ID = a['id']
return ID
def b(b):
Name = b['name']
return Name
def c(c):
description = c['description']
return description
data = var['data'] #I can get this working
print(data)
#cv = data['name'] #but this wont work
#id = a(var) #nor this
#name = b(var) #nor this
#desc = c(var) #nor this
#await ctx.send("\nID: " + id + "\nName: " + name + "\nDesc: " + desc) # this is just sending the message
client.run(BOT TOKEN HERE) #yes i did indeed add it but just for the question i removed it
As I said in the code, I can only get "data" working and not id,name or desc. For id name and desc it just throws an error
Ignoring exception in command findfriends:
Traceback (most recent call last):
File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 79, in wrapped
ret = await coro(*args, **kwargs)
File "C:/Users/Calculator/PycharmProjects/ryhrthrthrhrebnfbngfbfg/a.py", line 277, in findfriends
id = a(var) #nor this
File "C:/Users/Calculator/PycharmProjects/ryhrthrthrhrebnfbngfbfg/a.py", line 266, in a
ID = a['id']
KeyError: 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\bot.py", line 863, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 728, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 88, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'id'
and
Ignoring exception in command findfriends:
Traceback (most recent call last):
File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 79, in wrapped
ret = await coro(*args, **kwargs)
File "C:/Users/Calculator/PycharmProjects/ryhrthrthrhrebnfbngfbfg/a.py", line 274, in findfriends
data = var['data']['id'] #I can get this working
TypeError: list indices must be integers or slices, not str
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\bot.py", line 863, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 728, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 88, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str
The https://friends.roblox.com/v1/users/<userid>/friends endpoint returns a list of all the friends that the user has, which can be of varying size.
With var = json.loads(res.text) you are loading the response text into a json object, which contains the key data, which you access using data = var['data']. The new data variable now contains a list object, which is why cv = data['name'] fails to work as list objects do not take strings as keys, they are accessed using integers.
You need to iterate over the list to get all information on the friends. The below code goes through the list, pulls information for each item in the list and sends a message of the information once it has gone through all items.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import requests, json
import asyncio
client = commands.Bot(command_prefix='?')
#client.event
async def on_ready():
print('started')
#client.command()
async def findfriends(ctx,userid):
res = requests.get("https://friends.roblox.com/v1/users/"+userid+"/friends")
var = json.loads(res.text)
data = var['data']
print(data)
friends_msg = 'Friends information:'
for friend in data:
id = friend['id']
name = friend['name']
desc = friend['description']
friends_msg = friends_msg + "\nID: " + id + "\nName: " + name + "\nDesc: " + desc
await ctx.send(friends_msg)
client.run(BOT TOKEN HERE)
Related
This is my code:
#client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
emb = discord.Embed(color=0xda70d6,title = 'Issue with command', discription = 'Using the correct commands is helpful, if you dont know them use "_help"')
emb.set_author(name = 'Alert', icon_url='https://i.pinimg.com/474x/60/5e/ac/605eac3124c4885e067002cdd4ff684a.jpg')
emb.set_thumbnail('https://library.kissclipart.com/20191119/ww/kissclipart-help-icon-help-and-support-icon-92018307fcf5c4fa.png')
emb.set_footer('If you have any questions just DM the onwer Saly_Derek#0031 or Co-Owner Salty_Troye#0540')
await ctx.send(embed=emb)
When I use the command in my console I get this error:
Ignoring exception in on_command_error
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 58, in on_command_error
emb.set_thumbnail('https://library.kissclipart.com/20191119/ww/kissclipart-help-icon-help-and-support-icon-92018307fcf5c4fa.png')
TypeError: set_thumbnail() takes 1 positional argument but 2 were given
But I don't know what's wrong or how to fix it.
Fixed my issue, this works 100%. My issue was for emb.set_thumbnail I never had "url = 'link'"
#client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
emb = discord.Embed(color=0xda70d6,title = 'Issue with command', description = f'''using commands properly is helpful. Use command "_help"''')
emb.set_author(name = 'Alert', icon_url = 'https://i.pinimg.com/474x/60/5e/ac/605eac3124c4885e067002cdd4ff684a.jpg')
emb.set_thumbnail(url = 'https://library.kissclipart.com/20191119/ww/kissclipart-help-icon-help-and-support-icon-92018307fcf5c4fa.png')
emb.set_footer(text = f'If you have any questions just DM the onwer Saly_Derek#0031 or Co-Owner Salty_Troye#0540')
await ctx.send(embed=emb)```
I am a beginner in Python, and trying out making a bot which automatically Tweets anything which is posted on a Subreddit that I have made.
I took help from some of the tutorials online which has the following code
import praw
import json
import requests
import tweepy
import time
access_token = '************************************'
access_token_secret = '************************************'
consumer_key = '************************************'
consumer_secret = '************************************'
def strip_title(title):
if len(title) == 94:
return title
else:
return title[:93] + "..."
def tweet_creator(subreddit_info):
post_dict = {}
post_ids = []
print("[bot] Getting posts from Reddit")
for submission in subreddit_info.get_hot(limit=20):
post_dict[strip_title(submission.title)] = submission.url
post_ids.append(submission.id)
print("[bot] Generating short link using goo.gl")
mini_post_dict = {}
for post in post_dict:
post_title = post
post_link = post_dict[post]
short_link = shorten(post_link)
mini_post_dict[post_title] = short_link
return mini_post_dict, post_ids
def setup_connection_reddit(subreddit):
print("[bot] setting up connection with Reddit")
r = praw.Reddit(' %s' %(subreddit))
subreddit = r.get_subreddit(subreddit)
return subreddit
def shorten(url):
headers = {'content-type': 'application/json'}
payload = {"longUrl": url}
url = "https://www.googleapis.com/urlshortener/v1/url"
r = requests.post(url, data=json.dumps(payload), headers=headers)
link = json.loads(r.text)['id']
return link
def duplicate_check(id):
found = 0
with open('posted_posts.txt', 'r') as file:
for line in file:
if id in line:
found = 1
return found
def add_id_to_file(id):
with open('posted_posts.txt', 'a') as file:
file.write(str(id) + "\n")
def main():
subreddit = setup_connection_reddit('*Name of the subreddit*')
post_dict, post_ids = tweet_creator(subreddit)
tweeter(post_dict, post_ids)
def tweeter(post_dict, post_ids):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
for post, post_id in zip(post_dict, post_ids):
found = duplicate_check(post_id)
if found == 0:
print("[bot] Posting this link on twitter")
print(post + " " + post_dict[post] + " #Python #reddit #bot")
api.update_status(post+" "+post_dict[post]+" #Python #reddit #bot")
add_id_to_file(post_id)
time.sleep(30)
else:
print("[bot] Already posted")
if __name__ == '__main__':
main()
The code seems fine in PyCharm, however I am getting the following error when I try to run it directly from the folder via Terminal using the rolling code, reddit_bot2.py is my file name:
python3 reddit_bot2.py
When I try to run the code I am getting the following error:
mahesh#Maheshs-MacBook-Air Atoms % python3 reddit_bot2.py
[bot] setting up connection with Reddit
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/configparser.py", line 846, in items
d.update(self._sections[section])
KeyError: '**Name of the subreddit to fetch posts from**'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/mahesh/Python_Bot/Atoms/reddit_bot2.py", line 82, in <module>
main()
File "/Users/mahesh/Python_Bot/Atoms/reddit_bot2.py", line 62, in main
subreddit = setup_connection_reddit('Bot167')
File "/Users/mahesh/Python_Bot/Atoms/reddit_bot2.py", line 36, in setup_connection_reddit
r = praw.Reddit(' %s' %(subreddit))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/praw/reddit.py", line 227, in __init__
self.config = Config(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/praw/config.py", line 85, in __init__
self.custom = dict(Config.CONFIG.items(site_name), **settings)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/configparser.py", line 849, in items
raise NoSectionError(section)
configparser.NoSectionError: No section: ' Bot167'
You provided the name of a praw.ini configuration which does not exist.
For help with creating a Reddit instance, visit
https://praw.readthedocs.io/en/latest/code_overview/reddit_instance.html
For help on configuring PRAW, visit
https://praw.readthedocs.io/en/latest/getting_started/configuration.html
Any help in this regards would be highly appreciated.
Thanks :)
Sitting and studying information about the discord.py 0.16.12 I was interested in the function discord.Client.edit_role(server,role,parametrs*)
I ran into a problem(An hour before that everything worked)
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\ROG\Desktop\trash\dsbt\venv\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:/Users/ROG/Desktop/trash/dsbt/rainbown_rolle/testbd.py", line 10, in on_ready
await bot.edit_role(sr, rl, colour=discord.Colour(((rgb[0] << 16) + (rgb[1] << 8) + rgb[2])))
File "C:\Users\ROG\Desktop\trash\dsbt\venv\lib\site-packages\discord\client.py", line 2860, in edit_role
yield from self.http.edit_role(server.id, role.id, **payload)
File "C:\Users\ROG\Desktop\trash\dsbt\venv\lib\site-packages\discord\http.py", line 169, in request
print(data['retry_after'])
TypeError: string indices must be integers
Bot code
import discord
token="token"
bot=discord.Client()
#bot.event
async def on_ready():
rgb = [255, 0, 161]
sr= discord.utils.find(lambda m: m.id == '403945874780061707',bot.servers)
rl = discord.utils.find(lambda m: m.name == "Обыватель", sr.roles)
print(type(sr),type(rl))
await bot.edit_role(sr, rl, colour=discord.Colour(((rgb[0] << 16) + (rgb[1] << 8) + rgb[2])))
bot.run(token)
It looks like the endpoint returned some response body that was just text, not a json.
discord.py expects responses with status 429 (rate limited) to be a json it can turn into a dictionary. So it's trying to access the text like a dictionary, which fails.
According to this commit which fixes this issue for the rewrite branch, it may be that you've been banned by Cloudflare. Try updating your bot to the new version, but you will most likely have to host your bot somewhere else to get around whatever ban they have in place.
I have following code which creates a testrail client and executes testrail's GET_SUITES API call.
I have a function to call the GET_SUITES API and I am passing testrail client & test_rail_project_id as params
I am trying to use multiprocessing to execute over my list of projects to speed up things and I am can't pickle error
My code:
from itertools import product
def get_suites(client, project_id):
try:
path = 'get_suites/{projectid}'.format(projectid=project_id)
test_rail_response = client.send_get(path)
return test_rail_response
except Exception as e:
raise Exception(str(e))
if __name__ == "__main__":
testRailClient = APIClient(TESTRAIL_URL)
pool = Pool(2)
all_project_ids = [100, 200, 300]
data = pool.starmap(get_suites, product([testRailClient], all_project_ids))
Error stack:
Traceback (most recent call last):
File "main.py", line 57, in <module>
data = pool.starmap(testrailapi.get_suites, product([testRailClient], all_project_ids))
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 274, in starmap
return self._map_async(func, iterable, starmapstar, chunksize).get()
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 644, in get
raise self._value
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 424, in _handle_tasks
put(task)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
TypeError: can't pickle SSLContext objects
Any suggestions please?
Thank you
PS: I am using Python3.6
UPDATE:
As suggested I tried removing the API client as a parameter and it worked but I am getting the same error when I have "get_suites" as a method. Please see my updated code below
class TestRailExecution:
def __init__(self, url, username, password):
self.url = url
self.username = username
self.password = password
self.client = APIClient(self.url)
self.client.user = username
self.client.password = password
def get_suites(self, project_id):
try:
path = 'get_suites/{projectid}'.format(projectid=project_id)
test_rail_response = self.client.send_get(path)
return test_rail_response
except Exception as e:
raise Exception(str(e))
if __name__ == "__main__":
testRailClient = TestRailExecution(TESTRAIL_URL, user, password)
pool = Pool(2)
data = pool.map(get_suites, [100, 200, 300])
i am puzzled getting the following to work with asyncio:
the code snippet below is querying a number devices (via snmp) and returns a dictionary, it works fine, but is limited by multiprocessing.cpu_count()
def do_polling(netelement, snmp_comm):
msg = {}
msg.update({
'bgp' : do_lookup_bgp(netelement, snmp_comm),
'iface' : do_lookup_iface(netelement, snmp_comm),
'ifidx' : do_lookup_ifindex(netelement, snmp_comm),
'agg' : do_lookup_agg(netelement, snmp_comm),
})
return msg
def save(netelement, job):
data[netelement] = job.result()
with concurrent.futures.ProcessPoolExecutor(max_workers=multiprocessing.cpu_count()) as executor:
for k,v in INFO['dev'].items():
job = executor.submit(do_polling, k, v['snmp_comm'])
job.add_done_callback(functools.partial(save, k))
so i would like to migrate to the asyncio approach by changing like this:
#asyncio.coroutine
def do_polling(netelement, snmp_comm):
msg = {}
msg['bgp'] = yield from do_lookup_bgp(netelement, snmp_comm)
msg['iface'] = yield from do_lookup_iface(netelement, snmp_comm)
msg['ifidx'] = yield from do_lookup_ifindex(netelement, snmp_comm)
msg['agg'] = yield from do_lookup_agg(netelement, snmp_comm)
#asyncio.coroutine
def schedule(INFO):
for k,v in INFO['dev'].items():
asyncio.async(do_polling(k, v))
asyncio.get_event_loop().run_until_complete(schedule)
but i am getting the following error:
Traceback (most recent call last):
File "/home/app/ip-spotlight/code/ixmac.py", line 60, in <module>
main()
File "/home/app/ip-spotlight/code/ixmac.py", line 16, in main
app.ixmac.initialize.run(INFO)
File "/home/app/ip-spotlight/code/app/ixmac/initialize.py", line 191, in run
asyncio.get_event_loop().run_until_complete(schedule)
File "/usr/lib64/python3.4/asyncio/base_events.py", line 353, in run_until_complete
future = tasks.ensure_future(future, loop=self)
File "/usr/lib64/python3.4/asyncio/tasks.py", line 553, in ensure_future
raise TypeError('A Future, a coroutine or an awaitable is required')
TypeError: A Future, a coroutine or an awaitable is required
could you please advise what i am doing wrong ?
You are not using it as a coroutine. You should change the last line to:
asyncio.get_event_loop().run_until_complete(schedule(the_info_variable))