So I have been working on a chat room client, except I have one problem. I have been wanting to be able to list who is online and the easiest way I would do that would be with variables. I would have a starting variable that would be for example:
OnlineClients = []
Which other clients when they join I want their client to send the variable 'OnlineClients.append(name)' to add it to the list. When they quit it should also send the command 'OnlineClients.remove(name)'. Is there any way I can do this?
This is a snippet of my code of my attempts to send variables:
#This list is important because it is used for listing who is on the chat
OnlineClients = ["Person1", "Person2", "Person3"]
ListOnline = (" ".join(OnlineClients))
#THIS IS TEST 1 FOR VARIABLE SENDING
#In future update remove own name from online list
#!to_varlist = (OnlineClients.append(name))
s.send(OnlineClients.append("Apple").encode())
#to_send = (person1 = name)
#s.send(to_send.encode())
#to_var = a = b
#s.send(to_var.encode())
#s.send(a=b.encode())
Related
So far, I have the following function that checks NLP values of the messages that user sends to the chatbot. I would want to store these values so that if user sends 10 messages, textToneSum is the sum of all textTone values. I will use this data later in another function with help of Session. However, as the chat function is called with AJAX every time user clicks a button to send a message, textToneSum never gathers values from more than one message. How would I solve this? There is probably an easy solution but my brain feels stuck.
#app.route('/chat', methods=['GET','POST'])
def chat():
textToneSum = 0
message = request.args.get('message')
textSample = TextBlob (message)
textTone = textSample.sentiment.polarity
textSubj = textSample.sentiment.subjectivity
textToneSum+=textTone
print("sum is", textToneSum)
#some irrelevant code deleted here
session['textToneSum'] = textToneSum
return jsonify(result = response_text, texttone = textTone, textsubj = textSubj)
I am attempting to create a small dataset by pulling messages/responses from a slack channel I am a part of. I would like to use python to pull the data from the channel however I am having trouble figuring out my api key. I have created an app on slack but I am not sure how to find my api key. I see my client secret, signing secret, and verification token but can't find my api key
Here is a basic example of what I believe I am trying to accomplish:
import slack
sc = slack.SlackClient("api key")
sc.api_call(
"channels.history",
channel="C0XXXXXX"
)
I am willing to just download the data manually if that is possible as well. Any help is greatly appreciated.
messages
See below for is an example code on how to pull messages from a channel in Python.
It uses the official Python Slack library and calls
conversations_history with paging. It will therefore work with
any type of channel and can fetch large amounts of messages if
needed.
The result will be written to a file as JSON array.
You can specify channel and max message to be retrieved
threads
Note that the conversations.history endpoint will not return thread messages. Those have to be retrieved additionaly with one call to conversations.replies for every thread you want to retrieve messages for.
Threads can be identified in the messages for each channel by checking for the threads_ts property in the message. If it exists there is a thread attached to it. See this page for more details on how threads work.
IDs
This script will not replace IDs with names though. If you need that here are some pointers how to implement it:
You need to replace IDs for users, channels, bots, usergroups (if on a paid plan)
You can fetch the lists for users, channels and usergroups from the API with users_list, conversations_list and usergroups_list respectively, bots need to be fetched one by one with bots_info (if needed)
IDs occur in many places in messages:
user top level property
bot_id top level property
as link in any property that allows text, e.g. <#U12345678> for users or <#C1234567> for channels. Those can occur in the top level text property, but also in attachments and blocks.
Example code
import os
import slack
import json
from time import sleep
CHANNEL = "C12345678"
MESSAGES_PER_PAGE = 200
MAX_MESSAGES = 1000
# init web client
client = slack.WebClient(token=os.environ['SLACK_TOKEN'])
# get first page
page = 1
print("Retrieving page {}".format(page))
response = client.conversations_history(
channel=CHANNEL,
limit=MESSAGES_PER_PAGE,
)
assert response["ok"]
messages_all = response['messages']
# get additional pages if below max message and if they are any
while len(messages_all) + MESSAGES_PER_PAGE <= MAX_MESSAGES and response['has_more']:
page += 1
print("Retrieving page {}".format(page))
sleep(1) # need to wait 1 sec before next call due to rate limits
response = client.conversations_history(
channel=CHANNEL,
limit=MESSAGES_PER_PAGE,
cursor=response['response_metadata']['next_cursor']
)
assert response["ok"]
messages = response['messages']
messages_all = messages_all + messages
print(
"Fetched a total of {} messages from channel {}".format(
len(messages_all),
CHANNEL
))
# write the result to a file
with open('messages.json', 'w', encoding='utf-8') as f:
json.dump(
messages_all,
f,
sort_keys=True,
indent=4,
ensure_ascii=False
)
This is using the slack webapi. You would need to install requests package. This should grab all the messages in channel. You need a token which can be grabbed from apps management page. And you can use the getChannels() function. Once you grab all the messages you will need to see who wrote what message you need to do id matching(map ids to usernames) you can use getUsers() functions. Follow this https://api.slack.com/custom-integrations/legacy-tokens to generate a legacy-token if you do not want to use a token from your app.
def getMessages(token, channelId):
print("Getting Messages")
# this function get all the messages from the slack team-search channel
# it will only get all the messages from the team-search channel
slack_url = "https://slack.com/api/conversations.history?token=" + token + "&channel=" + channelId
messages = requests.get(slack_url).json()
return messages
def getChannels(token):
'''
function returns an object containing a object containing all the
channels in a given workspace
'''
channelsURL = "https://slack.com/api/conversations.list?token=%s" % token
channelList = requests.get(channelsURL).json()["channels"] # an array of channels
channels = {}
# putting the channels and their ids into a dictonary
for channel in channelList:
channels[channel["name"]] = channel["id"]
return {"channels": channels}
def getUsers(token):
# this function get a list of users in workplace including bots
users = []
channelsURL = "https://slack.com/api/users.list?token=%s&pretty=1" % token
members = requests.get(channelsURL).json()["members"]
return members
I made a python script that crawls the web page at 'http://spys.one/en/socks-proxy-list/' and fetches all the IP addresses there, then checks if they're up and finally returns a list of all live Ip addresses. then there's a second script which connects to telegrams bot API and uses the first script to show the user a list of recent socks5 working servers.
I'm an amateur programmer and new to Python programming language. I made these scripts for exercise. feel free to point out my mistakes and show the ways I can improve my code. thanks in advance!
import requests as req
import re
import socket
def is_open(ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, int(port)))
s.shutdown(2)
return True
except:
return False
# Initial settings:
url = 'http://spys.one/en/socks-proxy-list/'
regex = '\d{1,4}\.\d{1,4}\.\d{1,4}\.\d{1,4}'
# Request URL
response = req.get(url).text
# Extract IP and port from source
p = re.compile(regex)
results = p.findall(response)
# Fetch and check the first 20 IPs
alive = []
for i in range(0, 20):
if is_open(results[i], '1080'):
alive.append(results[i])
def gimmeprox():
links = []
for x in range(0,len(alive)):
links.append('https://t.me/proxy?server=' + alive[int(x)] + '&port=1080')
payload = '\n\n'.join(links)
return payload
When I run this code and the other (bot) script, everything works fine, but as soon as I put it on the web (heroku, etc.) it crashes on line 30:
line 30, in <module>
if is_open(results[i], '1080'):
with the error "".
Short answer: "results" does not always have 20 items. So, you're basically asking for something that doesn't exist.
You should always check the length before iterating over; or in these scenarios when you don't need the index, simply iterate over the actual items rather than the index.
When you run
for i in range(20):
if is_open(results[i], '1080'):
alive.append(results[i])
and len(results) is <20, you will eventually try to access results[len(results)], resulting in an IndexError. To prevent this, choose the lower value of len(results) and 20 as your argument for range, like so: min(len(results), 20).
An alternative is to loop through all values of results and break when you have 20.
for r in result:
if is_open(r, '1080'):
alive.append(r)
if len(alive) >= 20: # shouldn't actually get over 20, just a precaution
break
Can anybody help me to fix this code, I really need it, but have no idea what to do next. I need to create a groupchat and send messega to invited persons, now it is example2#gmail.com, but it does not...
Is there mistake?
#!/usr/bin/python
import sys,os,xmpp,time
jid = 'example1#gmail.com'
psw = 'psw'
jid=xmpp.protocol.JID(jid)
cl=xmpp.Client(jid.getDomain(),debug=[])
cl.connect()
cl.auth(jid.getNode(),psw)
node = jid.getNode()
domain = 'talk.google.com'
room = node + '#' + domain
nroom = room + '/' + 'Maria'
mes = xmpp.Presence(to=nroom)
cl.sendInitPresence()
cl.send(mes)
NS_MUCUSER = 'http://jabber.org/protocol/muc#user'
invite = xmpp.simplexml.Node('invite')
invite.setAttr('to', 'example2#gmail.com')
invite.setTagData('reason', 'I really need it!')
mess = xmpp.Message(to=room)
mess.setTag('x', namespace=NS_MUCUSER).addChild(node=invite)
cl.send(mess)
msg = xmpp.protocol.Message(body="Hello there!")
msg.setTo(room)
msg.setType('groupchat')
cl.send(msg)
time.sleep(1) # some older servers will not send the message if you disconnect immediately after sending
cl.disconnect()
print "Done"
According to the specs - http://xmpp.org/extensions/xep-0045.html#createroom - sending a request to join a room that doesn't exist should create that room (or MUC)
The workflow for creating and configuring such rooms is as follows:
The user sends presence to <room#service/nick> and signal his or her support
for the Multi-User Chat protocol by including extended presence information
in an empty <x/> child element qualified by the 'http://jabber.org/protocol/muc'
namespace (note the lack of an '#owner' or '#user' fragment).
If this user is allowed to create a room and the room does not yet exist, the
service MUST create the room according to some default configuration, assign the
requesting user as the initial room owner, and add the owner to the room but not
allow anyone else to enter the room (effectively "locking" the room). The initial
presence stanza received by the owner from the room MUST include extended
presence information indicating the user's status as an owner and acknowledging
that the room has been created (via status code 201) and is awaiting
configuration.
So something like this is supposed to work according to the documentation.
jid=xmpp.protocol.JID('example#gmail.com')
cl=xmpp.Client(jid.getDomain(),debug=[])
jid = xmpp.protocol.JID('example#gmail.com')
client = xmpp.Client(jid.getDomain(), debug=[])
client.connect()
client.auth(jid.getNode(), 'my secret password')
client.send(xmpp.Presence(to='room#talk.google.com/ANick')
I find my mistake. Problem is that I didn't wait enough to get answer from the server and I invited people before server was able to create a chat room. Now I wait until I get answer from server and then send invite message.
I can't figure out the problem and want some input as to whether my Python code is incorrect, or if this is an issue or design limitation of Python XMPP library. I'm new to Python by the way.
Here's snippets of code in question below. What I'd like to do is read in a text file of IM recipients, one recipient per line, in XMPP/Jabber ID format. This is read into a Python list variable.
I then instantiate an XMPP client session and loop through the list of recipients and send a message to each recipient. Then sleep some time and repeat test. This is for load testing the IM client of recipients as well as IM server. There is code to alternately handle case of taking only one recipient from command line input instead of from file.
What ends up happening is that Python does iterate/loop through the list but only last recipient in list receives message. Switch order of recipients to verify. Kind of looks like Python XMPP library is not sending it out right, or I'm missing a step with the library calls, because the debug print statements during runtime indicate the looping works correctly.
recipient = ""
delay = 60
useFile = False
recList = []
...
elif (sys.argv[i] == '-t'):
recipient = sys.argv[i+1]
useFile = False
elif (sys.argv[i] == '-tf'):
fil = open(sys.argv[i+1], 'r')
recList = fil.readlines()
fil.close()
useFile = True
...
# disable debug msgs
cnx = xmpp.Client(svr,debug=[])
cnx.connect(server=(svr,5223))
cnx.auth(user,pwd,'imbot')
cnx.sendInitPresence()
while (True):
if useFile:
for listUser in recList:
cnx.send(xmpp.Message(listUser,msg+str(msgCounter)))
print "sending to "+listUser+" msg = "+msg+str(msgCounter)
else:
cnx.send(xmpp.Message(recipient,msg+str(msgCounter)))
msgCounter += 1
time.sleep(delay)
Never mind, found the problem. One has to watch out for the newline characters at the end of a line for the elements in a list returned by file.readlines(), so I had to strip it out with .rstrip('\n') on the element when sending out message.