Advertisement
Guest User

Untitled

a guest
Sep 15th, 2014
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.16 KB | None | 0 0
  1. ###
  2. # Copyright (c) 2013, Steven
  3. # All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are met:
  7. #
  8. # * Redistributions of source code must retain the above copyright notice,
  9. # this list of conditions, and the following disclaimer.
  10. # * Redistributions in binary form must reproduce the above copyright notice,
  11. # this list of conditions, and the following disclaimer in the
  12. # documentation and/or other materials provided with the distribution.
  13. # * Neither the name of the author of this software nor the name of
  14. # contributors to this software may be used to endorse or promote products
  15. # derived from this software without specific prior written consent.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  21. # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  23. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  24. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  25. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  27. # POSSIBILITY OF SUCH DAMAGE.
  28.  
  29. ###
  30. import os
  31. import time
  32. import random
  33. import inflect
  34.  
  35. #open is probably overshadowed by the imports
  36. _open=open
  37. import supybot.conf as conf
  38. import supybot.ircdb as ircdb
  39. import supybot.utils as utils
  40. from supybot.commands import *
  41. import supybot.plugins as plugins
  42. import supybot.ircutils as ircutils
  43. import supybot.callbacks as callbacks
  44. from supybot.conf import supybot
  45.  
  46. try:
  47. import sqlite3
  48. except ImportError:
  49. from pysqlite2 import dbapi2 as sqlite3 # for python2.4
  50.  
  51. color="12"
  52.  
  53. def _is_determiner(string):
  54. determiners = ['the', 'a', 'an', 'another', 'no', 'the', 'a', 'an',
  55. 'no', 'another', 'some', 'any', 'my', 'our', 'their',
  56. 'her', 'his', 'its', 'another', 'no', 'each', 'every',
  57. 'certain', 'its', 'another', 'no', 'this', 'that',
  58. 'all']
  59.  
  60. if string in determiners:
  61. return True
  62. elif string[-2:] == "'s":
  63. return True
  64. #any and __builtins__ are overshadowed
  65. #elif __builtins__.any(c.isdigit() for c in string):
  66. elif len([c for c in string if c in "1234567890"]) > 0:
  67. return True
  68. else:
  69. return False
  70.  
  71. class BakeIt(callbacks.Plugin, plugins.ChannelDBHandler):
  72. """bake [food]: bakes a food and adds it to the database
  73. eat [username]: consumes a food to remove it from the database"""
  74.  
  75. def __init__(self, irc):
  76. callbacks.Plugin.__init__(self, irc)
  77. plugins.ChannelDBHandler.__init__(self)
  78. exec open("plugins/BakeIt/foods.txt", "r").read()
  79. exec open("plugins/BakeIt/goods.txt", "r").read()
  80.  
  81. def makeDb(self, filename):
  82. if os.path.exists(filename):
  83. db = sqlite3.connect(filename)
  84. db.text_factory = str
  85. return db
  86. db = sqlite3.connect(filename)
  87. db.text_factory = str
  88. cursor = db.cursor()
  89. cursor.execute("""CREATE TABLE foods (
  90. id INTEGER PRIMARY KEY,
  91. foodname TEXT,
  92. added_at TIMESTAMP,
  93. baker TEXT,
  94. poisoned BOOLEAN,
  95. eater TEXT,
  96. cookverb TEXT
  97. )""")
  98. cursor.execute("""CREATE TABLE bakers (
  99. id INTEGER PRIMARY KEY,
  100. username TEXT UNIQUE ON CONFLICT REPLACE
  101. )""")
  102. db.commit()
  103. return db
  104.  
  105. def bake(self, irc, msg, args, channel, foodname):
  106. """[food]: bakes a food and adds it to the database.
  107.  
  108. A randomly selected default food choice is selected if one is not
  109. provided."""
  110. db = self.getDb(channel)
  111. cursor = db.cursor()
  112. p=inflect.engine()
  113.  
  114. username = msg.nick
  115.  
  116. if not foodname:
  117. foodname = random.choice(self.goods)
  118. capitals = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  119. lowers = "abcdefghijklmnopqrstuvwxyz"
  120. #if there is only one capitalized letter in the food name
  121. if len([c for c in foodname if c in capitals]) == 1:
  122. #if it is the first letter
  123. if foodname[0] in capitals:
  124. #lowercase it
  125. foodname = (lowers[capitals.index(foodname[0])]
  126. + foodname[1:])
  127.  
  128.  
  129. foodname = foodname.strip()
  130.  
  131. #start the food name with "a" or "an" if it is singular and this ins't already done
  132. if p.singular_noun(foodname):
  133. plural=True
  134. else:
  135. if not _is_determiner(foodname.split()[0]):
  136. foodname = p.a(foodname)
  137. plural=False
  138.  
  139. if random.random()<0.25:
  140. problem = random.choice(("knocked the food onto the floor",
  141. "overcooked the dough", "added salt instead of sugar",
  142. "let the plastic wrapping melt into the food",
  143. "sneezed onto the food"))
  144. response = ("You baked %s%s. Unfortunately, you %s and had to" +
  145. " discard it") % (color, foodname, problem)
  146. irc.reply(response)
  147. return
  148.  
  149. poisoned = random.randint(0, 1)
  150. cursor.execute("""INSERT INTO foods VALUES
  151. (NULL, ?, ?, ?, ?, NULL, 'baked')""",
  152. (foodname, int(time.time()), username, poisoned))
  153. cursor.execute("""INSERT INTO bakers VALUES
  154. (NULL, ?)""", [username])
  155. response = ("You baked %s%s. But whether or not %s poisonous " +
  156. "remains to be seen.") % (color, foodname, "they are" if plural else "it is")
  157. irc.reply(response)
  158.  
  159.  
  160. bake = wrap(bake, ['channel', additional('text')])
  161.  
  162. def cook(self, irc, msg, args, channel, foodname):
  163. """[food]: cooks a food and adds it to the database.
  164.  
  165. A randomly selected default food choice is selected if one is not
  166. provided."""
  167. db = self.getDb(channel)
  168. cursor = db.cursor()
  169. p=inflect.engine()
  170.  
  171. username = msg.nick
  172.  
  173. if not foodname:
  174. foodname = random.choice(self.foods)
  175. capitals = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  176. lowers = "abcdefghijklmnopqrstuvwxyz"
  177. #if there is only one capitalized letter in the food name
  178. if len([c for c in foodname if c in capitals]) == 1:
  179. #if it is the first letter
  180. if foodname[0] in capitals:
  181. #lowercase it
  182. foodname = (lowers[capitals.index(foodname[0])]
  183. + foodname[1:])
  184.  
  185.  
  186. foodname = foodname.strip()
  187.  
  188. #start the food name with "a" or "an" if it is singular and this ins't already done
  189. if p.singular_noun(foodname):
  190. plural=True
  191. else:
  192. if not _is_determiner(foodname.split()[0]):
  193. foodname = p.a(foodname)
  194. plural=False
  195.  
  196. if random.random()<0.25:
  197. problem = random.choice(("knocked the food onto the floor",
  198. "overcooked the dough", "added sugar instead of salt",
  199. "let the plastic wrapping melt into the food",
  200. "sneezed onto the food"))
  201. response = ("You cooked %s%s. Unfortunately, you %s and had to" +
  202. " discard it") % (color, foodname, problem)
  203. irc.reply(response)
  204. return
  205.  
  206. poisoned = random.randint(0, 1)
  207. cursor.execute("""INSERT INTO foods VALUES
  208. (NULL, ?, ?, ?, ?, NULL, 'cooked')""",
  209. (foodname, int(time.time()), username, poisoned))
  210. #not useful to call it the cooks table because that only
  211. #makes the code more complex
  212. cursor.execute("""INSERT INTO bakers VALUES
  213. (NULL, ?)""", [username])
  214. response = ("You cooked %s%s. But whether or not %s poisonous " +
  215. "remains to be seen.") % (color, foodname, "they are" if plural else "it is")
  216. irc.reply(response)
  217.  
  218.  
  219. cook = wrap(cook, ['channel', additional('text')])
  220.  
  221. def eat(self, irc, msg, args, channel, other):
  222. """[other]: consumes a food to remove it from the database.
  223.  
  224. Consumes a random food baked by other. If other is not provided,
  225. a randomly selected food not made by the consumer is eaten."""
  226. db = self.getDb(channel)
  227. cursor = db.cursor()
  228. p=inflect.engine()
  229.  
  230. username = msg.nick
  231.  
  232. if other:
  233. if username.lower() == other.lower():
  234. irc.reply("You can't eat your own food! " +
  235. "What if you poisoned yourself?!")
  236. return
  237. else:
  238. cursor.execute(
  239. """SELECT baker FROM foods WHERE eater IS NULL AND
  240. LOWER(baker) <> ?""",
  241. [username.lower()])
  242. others = [i[0] for i in cursor.fetchall()]
  243. #If the user selected nobody but there are still no goods
  244. #made by someone else
  245. if others == []:
  246. irc.reply("There are no goods available for you " +
  247. "to eat. Perhaps try baking something yourself.")
  248. return
  249. other = random.choice(others)
  250.  
  251.  
  252.  
  253.  
  254. cursor.execute("""SELECT * FROM foods WHERE LOWER(baker) = ?
  255. AND eater IS NULL""", [other.lower()])
  256. entries = cursor.fetchall()
  257.  
  258. #If the the person provided in the argument doesn't have anything
  259. #baked
  260. if entries == []:
  261. cursor.execute(
  262. """SELECT count(*) as cnt FROM bakers WHERE LOWER(username)
  263. = ?""",
  264. [other.lower()])
  265. other_has_baked = cursor.fetchone()[0] == (1,)
  266. #If the user selected someone who has never baked or cooked
  267. if other_has_baked:
  268. irc.reply(other + " has never prepared any food. " +
  269. "Perhaps you can try cooking or baking" +
  270. " something yourself.")
  271. return
  272.  
  273. #If the user selected someone who has baked in the past, but
  274. #everything made by the person has been eaten
  275. else:
  276. irc.reply(other + " does not currently have any foods " +
  277. "available for you to eat. Perhaps you " +
  278. "can try baking or cooking something yourself.")
  279. return
  280.  
  281. selected_entry = random.choice(entries)
  282. (id, foodname, added_at, baker, poisoned, eater, verb) = selected_entry
  283.  
  284. timediff = int(time.time()) - added_at
  285.  
  286. remarkprefix = "It seems that the" if poisoned else "The"
  287. remark = ("very deadly and you were poisoned" if poisoned==1 else
  288. "very delicious and you wanted to eat more")
  289.  
  290. #fpr the word after "which"
  291. inflection1 = "were" if p.singular_noun(foodname) else "was"
  292.  
  293. #for "goods were" or "good was"?
  294. #no longer used
  295. #inflection2 = "s were" if p.singular_noun(foodname) else " was"
  296.  
  297. SECONDS_PER_DAY = 86400.
  298. SECONDS_PER_HOUR = 3600.
  299. SECONDS_PER_MINUTE = 60.
  300. days = int(timediff / SECONDS_PER_DAY)
  301. hours = int((timediff - SECONDS_PER_DAY*days) / SECONDS_PER_HOUR)
  302. minutes = int((timediff - (days*SECONDS_PER_DAY) - \
  303. (hours*SECONDS_PER_HOUR)) / SECONDS_PER_MINUTE)
  304. seconds = int(timediff % 60)
  305. timenames = (" day", " hour", " minute", " second")
  306. timeparts = tuple(str(value) + p.plural(timenames[index], value)
  307. for index, value in enumerate((days, hours, minutes, seconds)))
  308.  
  309. if random.random()<0.25:
  310. problem = random.choice(("fell onto the floor",
  311. "had ants in it", "was moldy",
  312. "was recalled by the government",
  313. "got squished in the fridge"))
  314. response = ("You were going to eat %s%s which %s %s by %s about"
  315. + " %s, %s, %s, and %s ago. Unfortunately, the" +
  316. " food %s and you threw it away.") % \
  317. ((color, foodname, inflection1, verb, other) +
  318. timeparts + (problem,))
  319. cursor.execute("""UPDATE foods SET eater = 'dumpster' WHERE id = ?""",
  320. [id])
  321. else:
  322. response = ("You just ate %s%s which %s %s by %s about" +
  323. " %s, %s, %s, and %s ago." +
  324. " %s food was %s!") % \
  325. ((color, foodname, inflection1, verb, other) +
  326. timeparts + (remarkprefix, remark))
  327.  
  328.  
  329. cursor.execute("""UPDATE foods SET eater = ? WHERE id = ?""",
  330. [username, id])
  331. irc.reply(response)
  332.  
  333.  
  334. eat = wrap(eat, ['channel', additional('something')])
  335.  
  336. def food(self, irc, msg, args, channel, other):
  337. """: shows how much food you, or if entered, other
  338. has eaten and baked and how much of it is poisonous. """
  339. db = self.getDb(channel)
  340. cursor = db.cursor()
  341. p=inflect.engine()
  342.  
  343. username = msg.nick.lower()
  344. if other:
  345. other = other.lower()
  346.  
  347. if other:
  348. if username != other:
  349. irc.reply("Using this command on another person is" +
  350. " currently not supported.")
  351. return
  352. else:
  353. cursor.execute(
  354. """SELECT COUNT(*) as cnt FROM foods WHERE LOWER(baker) = ?
  355. AND verb = 'baked'""",
  356. [username])
  357. baked = cursor.fetchone()[0]
  358. cursor.execute(
  359. """SELECT COUNT(*) as cnt FROM foods WHERE LOWER(baker) = ? AND
  360. poisoned = 1 AND verb = 'baked'""",
  361. [username])
  362. baked_poison = cursor.fetchone()[0]
  363. cursor.execute(
  364. """SELECT COUNT(*) as cnt FROM foods WHERE LOWER(baker) = ?
  365. AND verb = 'cooked'""",
  366. [username])
  367. cooked = cursor.fetchone()[0]
  368. cursor.execute(
  369. """SELECT COUNT(*) as cnt FROM foods WHERE LOWER(baker) = ? AND
  370. poisoned = 1 AND verb = 'cooked'""",
  371. [username])
  372. cooked_poison = cursor.fetchone()[0]
  373. cursor.execute(
  374. """SELECT COUNT(*) as cnt FROM foods WHERE LOWER(eater) = ?""",
  375. [username])
  376. eaten = cursor.fetchone()[0]
  377. cursor.execute(
  378. """SELECT COUNT(*) as cnt FROM foods WHERE LOWER(eater) = ? AND
  379. poisoned = 1""",
  380. [username])
  381. eaten_poison = cursor.fetchone()[0]
  382. irc.reply("You have baked %s foods and %s of them were poisoned" %
  383. (baked, baked_poison))
  384. irc.reply("You have cooked %s foods and %s of them were poisoned" %
  385. (cooked, cooked_poison))
  386. irc.reply("You have eaten %s foods and %s of them were poisoned" %
  387. (eaten, eaten_poison))
  388.  
  389.  
  390. food = wrap(food, ['channel', additional('something')])
  391.  
  392.  
  393.  
  394.  
  395. Class = BakeIt
  396.  
  397.  
  398. # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement