Skip to content

Instantly share code, notes, and snippets.

@jayliew
Last active March 23, 2017 18:21
Show Gist options
  • Save jayliew/a773899fdf381879b3618790572a5a7f to your computer and use it in GitHub Desktop.
Save jayliew/a773899fdf381879b3618790572a5a7f to your computer and use it in GitHub Desktop.
groupme django python bot for springhaus
def groupme_springhaus_ops(request):
if settings.ENABLE_GROUPME_OPS == False:
return Http404
url = "https://api.groupme.com/v3/groups/" + settings.GROUPME_SPRINGHAUS_CORE_GROUP_ID_KEY + "/messages"
gmc = GroupMeControl.objects.all()[0]
last_seen_message_id = gmc.last_seen_id_str
print("starting ops. Last message id is: " + gmc.last_seen_id_str)
something_new_added = False
try:
r = requests.get(url, params={'token': settings.GROUPME_JLIEW_TOKEN,
'after_id': last_seen_message_id,
'limit': 100 }) # 100 is max
if len(r.json()['response']['messages']) > 0 : # if there are new messages since last checked
messages = r.json()['response']['messages']
for message in messages:
if message == None or message['text'] == None:
continue
u_message_text = message['text'] + u''
regex = '^bot\s(.+)'
if re.search(regex, u_message_text, re.IGNORECASE) != None:
print("DETECTED: " + u_message_text)
try:
household_item_name = re.search(regex, u_message_text, re.IGNORECASE).groups()[0]
# did this person append an irrelevant sentence not meant for bot, after a period?
if '.' in household_item_name:
household_item_name = household_item_name.split('.')[0]
if len(household_item_name) > 60:
l = household_item_name.split()
if len(l) > 5:
household_item_name = " ".join(l[:5]) # just grab first 5 words
if len(household_item_name) > 60: # if first 5 words still too long, trim
household_item_name = household_item_name[:60]
except:
household_item_name = "n0name"
# if user doesn't exist in local db, create
gmu, created = GroupMeUser.objects.get_or_create(id=int(message['sender_id']))
if created: # if new user created, save first name
first_name_regex = "\s*(\S+)"
if re.search(first_name_regex, message['name']) != None:
try:
gmu.name = re.search(first_name_regex, message['name']).groups()[0]
except:
gmu.name = "s0medude(th)"
print("NEW USER: " + gmu.name)
gmu.save()
items_bought_by_user = GroupMeHouseItem.objects.filter(user=gmu,
name__icontains=household_item_name)
if len(items_bought_by_user) == 0: # first time purchase of this item
new_item = GroupMeHouseItem()
new_item.user = gmu
new_item.name = household_item_name
new_item.count = 1
new_item.save()
print("NEW ITEM: " + new_item.name)
else: # if item was purchased before, just increase count
existing_item = items_bought_by_user[0]
existing_item.count += 1
existing_item.save()
print("EXISTING ITEM UPDATED COUNT = [" + str(existing_item.count) + "] " + existing_item.name)
something_new_added = True
else:
print("NOBOT: " + u_message_text)
# messages[len(messages)-1] is always the last message (most recent)
# update this so that don't grab repeat messages previously seen
first = int(messages[0]['id'])
last = int(messages[len(messages)-1]['id'])
if first > last:
gmc.last_seen_id_str = str(first)
print("last seen msg is: " + str(first))
else:
gmc.last_seen_id_str = str(last)
print("last seen msg is: " + str(last))
gmc.save()
except Exception, e:
print("SOMETHING BROKE " + str(e))
if something_new_added == True:
__groupme_springhaus_status() # only say something to group if something new added
return HttpResponse("OK")
def __groupme_springhaus_status():
url = "https://api.groupme.com/v3/bots/post"
try:
users = {}
for user in GroupMeUser.objects.all(): # get all users
users[user.name] = {}
for item in GroupMeHouseItem.objects.all(): # get everything they bought
users[item.user.name][item.name] = item.count
# flatten hash to text for Groupme
text = ""
for username in users.keys():
text += "[" + username + "] "
for item_name in users[username].keys():
text += item_name + " " + str(users[username][item_name]) + ", "
r = requests.post(url, {'bot_id': settings.GROUPME_BOT_ID_KEY, 'text': text})
except:
pass
return HttpResponse("NOT OK")
return HttpResponse("OK")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment